Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
bootstrap spree 6 docs (#14492)
Damian Legawiec31a1514aa0dd
diff --git a/docs/developer/cli/quickstart.mdx b/docs/developer/cli/quickstart.mdxindex 7c151a5155..abcf8ad5f3 100644--- a/docs/developer/cli/quickstart.mdx+++ b/docs/developer/cli/quickstart.mdx@@ -1,6 +1,6 @@---title: Spree CLI-sidebarTitle: Overview+sidebarTitle: Spree CLIdescription: Install and use the @spree/cli to scaffold, run, build, and migrate Spree projects — and call the Admin API directly from the command line.---diff --git a/docs/developer/contributing/creating-an-extension.mdx b/docs/developer/contributing/creating-an-extension.mdxindex 1d9b19af72..75f73588da 100644--- a/docs/developer/contributing/creating-an-extension.mdx+++ b/docs/developer/contributing/creating-an-extension.mdx@@ -239,8 +239,8 @@ While this tutorial uses decorators to extend Spree's core behavior, modern Spre| React to model changes | [Events subscribers](/developer/core-concepts/events) || External service integration | [Webhooks](/developer/core-concepts/webhooks) || Replace core services | [Dependencies injection](/developer/customization/dependencies) |-| Add admin UI elements | [Admin Partials](/developer/admin/extending-ui) |-| Add admin menu items | [Admin Navigation](/developer/admin/navigation) |+| Add admin UI elements | [Admin Partials](/developer/dashboard/customization/quickstart) |+| Add admin menu items | [Admin Navigation](/developer/dashboard/customization/navigation) |For example, if your extension needs to sync data with an external service when products are updated, use an Events subscriber instead of a decorator callback:diff --git a/docs/developer/core-concepts/addresses.mdx b/docs/developer/core-concepts/addresses.mdxindex 577e60b48f..61c728f942 100644--- a/docs/developer/core-concepts/addresses.mdx+++ b/docs/developer/core-concepts/addresses.mdx@@ -251,7 +251,7 @@ For countries without predefined states, addresses accept a free-text `state_nam## Zones-Zones group countries or states together for [tax](/developer/core-concepts/taxes) and [shipping](/developer/core-concepts/shipments) rules. A zone is either **country-based** or **state-based**.+Zones group countries or states together for [tax](/developer/core-concepts/taxes) and [shipping](/developer/core-concepts/fulfillments) rules. A zone is either **country-based** or **state-based**.**Examples:**- **EU VAT** (country zone) — Germany, France, Italy, Spain, ... → applies EU VAT rates@@ -260,7 +260,7 @@ Zones group countries or states together for [tax](/developer/core-concepts/taxeWhen a customer enters their address at checkout, Spree matches it against zones to determine:1. Which **tax rates** apply (see [Taxes](/developer/core-concepts/taxes))-2. Which **shipping methods** are available (see [Shipments](/developer/core-concepts/shipments))+2. Which **shipping methods** are available (see [Shipments](/developer/core-concepts/fulfillments))Zones are configured in the admin dashboard — storefront developers don't interact with them directly via the API.@@ -283,7 +283,7 @@ Here's how geography flows through a typical checkout:- [Markets](/developer/core-concepts/markets) — Multi-region commerce with currency, locale, and country grouping- [Taxes](/developer/core-concepts/taxes) — How zones and addresses affect taxation-- [Shipments](/developer/core-concepts/shipments) — How zones and addresses affect shipping availability+- [Shipments](/developer/core-concepts/fulfillments) — How zones and addresses affect shipping availability- [Orders](/developer/core-concepts/orders) — Order billing and shipping addresses- [Account SDK guide](/developer/sdk/store/account) — Managing the logged-in customer's address book with `client.customer.addresses`- [Store API authentication](/api-reference/store-api/authentication) — How to obtain and send the customer JWT (`Authorization: Bearer` header)diff --git a/docs/developer/core-concepts/architecture.mdx b/docs/developer/core-concepts/architecture.mdxindex 5368915c6e..1662fa4f3d 100644--- a/docs/developer/core-concepts/architecture.mdx+++ b/docs/developer/core-concepts/architecture.mdx@@ -59,11 +59,11 @@ flowchart TB2. **Shopping** — Customers add Variants to their cart, creating an [Order](/developer/core-concepts/orders) with Line Items-3. **Checkout** — The Order collects [Addresses](/developer/core-concepts/addresses), calculates [Shipping](/developer/core-concepts/shipments) options, and processes [Payments](/developer/core-concepts/payments)+3. **Checkout** — The Order collects [Addresses](/developer/core-concepts/addresses), calculates [Shipping](/developer/core-concepts/fulfillments) options, and processes [Payments](/developer/core-concepts/payments)-4. **Fulfillment** — [Shipments](/developer/core-concepts/shipments) are created from Stock Locations, tracking individual [Inventory Units](/developer/core-concepts/inventory#inventory-units)+4. **Fulfillment** — [Shipments](/developer/core-concepts/fulfillments) are created from Stock Locations, tracking individual [Inventory Units](/developer/core-concepts/inventory#inventory-units)-5. **Pricing & Adjustments** — [Taxes](/developer/core-concepts/taxes) and [Promotions](/developer/core-concepts/promotions) create [Adjustments](/developer/core-concepts/adjustments) that modify order totals+5. **Pricing & Adjustments** — [Taxes](/developer/core-concepts/taxes) and [Promotions](/developer/core-concepts/promotions) create [Adjustments](/developer/core-concepts/taxes-discounts-fees) that modify order totals## Core Model Relationships@@ -176,5 +176,5 @@ Spree is distributed as a set of packages:- [Products](/developer/core-concepts/products) — Product catalog and variants- [Orders](/developer/core-concepts/orders) — Order lifecycle and state machine- [Payments](/developer/core-concepts/payments) — Payment processing-- [Shipments](/developer/core-concepts/shipments) — Shipping and fulfillment+- [Shipments](/developer/core-concepts/fulfillments) — Shipping and fulfillment- [Customization Quickstart](/developer/customization/quickstart) — How to extend Spreediff --git a/docs/developer/core-concepts/calculators.mdx b/docs/developer/core-concepts/calculators.mdxindex 0ad47db44f..6f5c2188ed 100644--- a/docs/developer/core-concepts/calculators.mdx+++ b/docs/developer/core-concepts/calculators.mdx@@ -45,7 +45,7 @@ erDiagram**Key relationships:**- **Calculator** computes amounts for various features- Used by **[Tax Rates](/developer/core-concepts/taxes)** to calculate tax amounts-- Used by **[Shipping Methods](/developer/core-concepts/shipments)** to calculate shipping costs+- Used by **[Shipping Methods](/developer/core-concepts/fulfillments)** to calculate shipping costs- Used by **[Promotion Actions](/developer/core-concepts/promotions)** to calculate discounts- Calculators store [preferences (rates, percentages, etc.)](/developer/customization/model-preferences) for their calculations@@ -299,6 +299,6 @@ The module does not define `create_adjustment`, `update_adjustment`, or `compute## Related Documentation-- [Adjustments](/developer/core-concepts/adjustments) — the records calculators compute amounts for.+- [Adjustments](/developer/core-concepts/taxes-discounts-fees) — the records calculators compute amounts for.- [Dependencies](/developer/customization/dependencies) — swap out calculators via the Dependencies system.diff --git a/docs/v6/developer/core-concepts/carts.mdx b/docs/developer/core-concepts/carts.mdxsimilarity index 94%rename from docs/v6/developer/core-concepts/carts.mdxrename to docs/developer/core-concepts/carts.mdxindex b36ac530cd..187b11ce30 100644--- a/docs/v6/developer/core-concepts/carts.mdx+++ b/docs/developer/core-concepts/carts.mdx@@ -5,7 +5,7 @@ description: How Spree models the shopping and checkout phase — a cart collect## Overview-A cart is everything that happens before a purchase is final: adding items, entering an address, choosing delivery, and paying. Completing a cart creates an [Order](/v6/developer/core-concepts/orders) — a separate, permanent record.+A cart is everything that happens before a purchase is final: adding items, entering an address, choosing delivery, and paying. Completing a cart creates an [Order](/developer/core-concepts/orders) — a separate, permanent record.The two are kept apart because they want opposite things. A cart changes constantly, tolerates half-finished states, and is often abandoned. An order is a financial record: it must not change quietly, and it has to keep saying what the customer actually agreed to pay.@@ -146,7 +146,7 @@ This is what lets you design your own checkout. Spree tells you what's missing;```</Step><Step title="Choose delivery">- Each [fulfillment](/v6/developer/core-concepts/fulfillments) offers delivery rates. Pick one per fulfillment.+ Each [fulfillment](/developer/core-concepts/fulfillments) offers delivery rates. Pick one per fulfillment.```typescript Store SDKconst cart = await client.carts.get(cartId)@@ -172,7 +172,7 @@ This is what lets you design your own checkout. Spree tells you what's missing;const order = await client.carts.complete(cartId)```- You get back an [Order](/v6/developer/core-concepts/orders).+ You get back an [Order](/developer/core-concepts/orders).</Step></Steps>@@ -204,6 +204,6 @@ Completed carts are kept rather than deleted, and an order records which cart it## Related-- [Orders](/v6/developer/core-concepts/orders) — the record a cart becomes+- [Orders](/developer/core-concepts/orders) — the record a cart becomes- [Payments](/developer/core-concepts/payments) — payment methods and sessions-- [Fulfillments](/v6/developer/core-concepts/fulfillments) — delivery options+- [Fulfillments](/developer/core-concepts/fulfillments) — delivery optionsdiff --git a/docs/developer/core-concepts/channels.mdx b/docs/developer/core-concepts/channels.mdxindex 52e1a9372f..e965a8a261 100644--- a/docs/developer/core-concepts/channels.mdx+++ b/docs/developer/core-concepts/channels.mdx@@ -23,7 +23,7 @@ Every store ships with one default channel named *Online Store*. You can add mor| `default` | Exactly one channel per store is the default. Used as a fallback when no channel header is present and as the auto-publish target for new products | `true` || `storefront_access` | Controls what an anonymous visitor may see: `public`, `prices_hidden`, or `login_required`. Unset inherits the store's setting. See [Storefront Access Gating](#storefront-access-gating) | `login_required` || `guest_checkout` | Whether an order may be placed without an account on this channel. Unset inherits the store's setting | `false` |-| `preferred_order_routing_strategy` | Optional per-channel override of the store's [Order Routing](/developer/core-concepts/shipments#order-routing) strategy | `Spree::OrderRouting::Strategy::Rules` |+| `preferred_order_routing_strategy` | Optional per-channel override of the store's [Order Routing](/developer/core-concepts/fulfillments#order-routing) strategy | `Spree::OrderRouting::Strategy::Rules` |`code` is normalized to a URL-safe slug on save — `POS` becomes `pos`, `Point of Sale!` becomes `point-of-sale`. Leaving `code` blank derives it from `name`.@@ -92,7 +92,7 @@ Product status (`draft` / `active` / `archived`) is the **outer gate**: a DraftEvery order is attributed to one channel. The channel is set from the `X-Spree-Channel` header on cart creation, from the merchant's selection on the "New order" form, or defaults to the store's primary channel.-This attribution drives reporting (best-selling by channel, revenue per channel) and per-channel order routing — see [Order Routing](/developer/core-concepts/shipments#order-routing).+This attribution drives reporting (best-selling by channel, revenue per channel) and per-channel order routing — see [Order Routing](/developer/core-concepts/fulfillments#order-routing).### Storefront Access Gating@@ -227,7 +227,7 @@ The write contract is **full-set**: the array represents the complete desired st- [Stores](/developer/core-concepts/stores) — Channels belong to a store- [Markets](/developer/core-concepts/markets) — Different from channels: markets segment geography/currency, channels segment selling surfaces- [Products](/developer/core-concepts/products) — Product catalog and publication-- [Order Routing](/developer/core-concepts/shipments#order-routing) — Channels can override the store's routing strategy+- [Order Routing](/developer/core-concepts/fulfillments#order-routing) — Channels can override the store's routing strategy- [Store SDK: Products](/developer/sdk/store/products) — Channel-scoped product listing and filtering- [Admin SDK: Resources](/developer/sdk/admin/resources) — How `adminClient.channels.addProducts` and other resource methods are structured- [Wholesale Portal](/developer/storefront/nextjs/wholesale) — A gated channel driving the Next.js storefront's B2B surfacediff --git a/docs/developer/core-concepts/customers.mdx b/docs/developer/core-concepts/customers.mdxindex 5a546f419a..24404c945b 100644--- a/docs/developer/core-concepts/customers.mdx+++ b/docs/developer/core-concepts/customers.mdx@@ -324,5 +324,5 @@ Customers don't need to register to purchase. Guest checkout uses an order token- [Account (Store SDK)](/developer/sdk/store/account) — Task-oriented walkthrough of registration, login, profile, addresses, and order history- [Addresses](/developer/core-concepts/addresses) — Customer address management- [Orders](/developer/core-concepts/orders) — Order history and checkout-- [Authentication](/developer/customization/authentication) — Custom authentication setup+- [Authentication](/developer/providers/sso) — Custom authentication setup- [Staff & Roles](/developer/core-concepts/staff-roles) — Admin users and permissionsdiff --git a/docs/developer/core-concepts/events.mdx b/docs/developer/core-concepts/events.mdxindex cb06b4b4d3..c1444dea6f 100644--- a/docs/developer/core-concepts/events.mdx+++ b/docs/developer/core-concepts/events.mdx@@ -662,4 +662,4 @@ See `Spree::Events::Adapters::ActiveSupportNotifications` for a complete referen- [Webhooks & Events Reference](/api-reference/webhooks-events) - Catalog of event and webhook payloads- [Customization Quickstart](/developer/customization/quickstart) - Overview of all customization options- [Decorators](/developer/customization/decorators) - When to use decorators vs events-- [Checkout Flow](/developer/customization/checkout) - Using events in checkout customization+- [Checkout Flow](/developer/core-concepts/carts) - Using events in checkout customizationdiff --git a/docs/v6/developer/core-concepts/fulfillments.mdx b/docs/developer/core-concepts/fulfillments.mdxsimilarity index 97%rename from docs/v6/developer/core-concepts/fulfillments.mdxrename to docs/developer/core-concepts/fulfillments.mdxindex 310f28451d..86b5e3b308 100644--- a/docs/v6/developer/core-concepts/fulfillments.mdx+++ b/docs/developer/core-concepts/fulfillments.mdx@@ -51,7 +51,7 @@ A fulfillment's status says what **you** did with the parcel — nothing else.| `delivered` | The customer has it || `canceled` | It won't be sent |-Statuses only move forward: once something has gone out it stays gone out, and a later payment problem changes the order's [payment status](/v6/developer/core-concepts/orders#statuses) rather than the fulfillment.+Statuses only move forward: once something has gone out it stays gone out, and a later payment problem changes the order's [payment status](/developer/core-concepts/orders#statuses) rather than the fulfillment.Whether a fulfillment *can* go out — the order is paid, nothing is on backorder — is checked when you fulfill it, and the answer comes back with a reason. It is not baked into the status, so a refund never moves a parcel backwards. Staff who need to ship against an invoice can pass `force`.@@ -281,6 +281,6 @@ Fulfillments publish [events](/developer/core-concepts/events) — `fulfillment.## Related-- [Orders](/v6/developer/core-concepts/orders) — how delivery status rolls up+- [Orders](/developer/core-concepts/orders) — how delivery status rolls up- [Inventory](/developer/core-concepts/inventory) — stock locations and availability-- [Returns, Exchanges & Claims](/v6/developer/core-concepts/returns-exchanges-claims) — items coming back+- [Returns, Exchanges & Claims](/developer/core-concepts/returns-exchanges-claims) — items coming backdiff --git a/docs/developer/core-concepts/imports-exports.mdx b/docs/developer/core-concepts/imports-exports.mdxindex 2c9d83454f..7bbc54dd0a 100644--- a/docs/developer/core-concepts/imports-exports.mdx+++ b/docs/developer/core-concepts/imports-exports.mdx@@ -270,24 +270,12 @@ module Spreehas_many :mappings # Field mappingshas_many :rows # CSV rows to process- # State machine- state_machine initial: :pending do- event :start_mapping do- transition to: :mapping- end- event :complete_mapping do- transition from: :mapping, to: :completed_mapping- end- event :start_processing do- transition from: :completed_mapping, to: :processing- end- event :complete do- transition from: :processing, to: :completed- end- event :fail do- transition to: :failed- end- end+ # Statuses. Each move between them is a workflow — Spree::Imports::+ # StartMapping, CompleteMapping, StartProcessing, Complete and+ # RetryFailedRows — so every step of the pipeline can be hooked.+ include Spree::HasStatus+ has_status :pending, :mapping, :completed_mapping, :processing, :completed, :failed,+ default: :pending# Key methodsdef import_schema # Returns schema class instancediff --git a/docs/developer/core-concepts/inventory.mdx b/docs/developer/core-concepts/inventory.mdxindex 93171db70c..729f319e0c 100644--- a/docs/developer/core-concepts/inventory.mdx+++ b/docs/developer/core-concepts/inventory.mdx@@ -82,7 +82,7 @@ erDiagram- **Stock Item** → Tracks quantity (`count_on_hand`) for a specific Variant at a specific Stock Location- **Stock Movement** → Records changes to Stock Item quantities (purchases, returns, transfers)- **Stock Transfer** → Moves inventory between Stock Locations, creating Stock Movements at source and destination-- **Inventory Unit** → Represents individual units in [Orders](/developer/core-concepts/orders) and [Shipments](/developer/core-concepts/shipments)+- **Inventory Unit** → Represents individual units in [Orders](/developer/core-concepts/orders) and [Shipments](/developer/core-concepts/fulfillments)- **Stock Reservation** → Time-limited soft hold on a Stock Item during checkout, scoped to a specific Order and Line Item## Inventory Management@@ -284,7 +284,7 @@ When a cart change in checkout would push the order beyond available stock, the### Background expiry-Abandoned checkouts leave behind expired reservation rows. Spree provides a job to clean them up but does **not** auto-schedule it — your application's job runner needs to invoke it periodically (every minute is typical). See the [5.4 to 5.5 upgrade guide](/developer/upgrades/5.4-to-5.5#schedule-the-stock-reservations-expiry-job) for sidekiq-cron, solid_queue, and good_job snippets.+Abandoned checkouts leave behind expired reservation rows. Spree provides a job to clean them up but does **not** auto-schedule it — your application's job runner needs to invoke it periodically (every minute is typical). See the [5.4 to 5.5 upgrade guide](/v5/developer/upgrades/5.4-to-5.5#schedule-the-stock-reservations-expiry-job) for sidekiq-cron, solid_queue, and good_job snippets.### Backorderable items@@ -329,7 +329,7 @@ If you don't need to track inventory, you can disable it:## Related Documentation- [Products](/developer/core-concepts/products) - Product and variant management-- [Shipments](/developer/core-concepts/shipments) - How inventory relates to shipments+- [Shipments](/developer/core-concepts/fulfillments) - How inventory relates to shipments- [Orders](/developer/core-concepts/orders) - How inventory is allocated to orders- [Admin SDK resources](/developer/sdk/admin/resources) - `stockLocations`, `stockItems`, and `stockTransfers` methods used in the examples above- [Admin API authentication](/api-reference/admin-api/authentication) - How to obtain and scope the secret key (`sk_xxx`) used by these callsdiff --git a/docs/developer/core-concepts/media.mdx b/docs/developer/core-concepts/media.mdxindex 2a8637f6ca..f8b8044d63 100644--- a/docs/developer/core-concepts/media.mdx+++ b/docs/developer/core-concepts/media.mdx@@ -112,7 +112,7 @@ Variants belonging to a different product are silently dropped — the API rejecThe Store API's `media` field on a product returns its gallery — product-level media when present, falling back to legacy variant-pinned images during the transition. On a variant, `media` returns the assets linked to that variant via `variant_ids`, falling back to direct variant uploads.-This dual rendering means existing storefronts keep working during the upgrade; new uploads attach to the product, and you opt into a [one-shot migration](/developer/upgrades/5.4-to-5.5) to re-home legacy variant-pinned data when convenient.+This dual rendering means existing storefronts keep working during the upgrade; new uploads attach to the product, and you opt into a [one-shot migration](/v5/developer/upgrades/5.4-to-5.5) to re-home legacy variant-pinned data when convenient.### Video <Since version="6.0" />diff --git a/docs/developer/core-concepts/metafields.mdx b/docs/developer/core-concepts/metafields.mdxindex 29e702f708..cdc54d7f2b 100644--- a/docs/developer/core-concepts/metafields.mdx+++ b/docs/developer/core-concepts/metafields.mdx@@ -296,7 +296,7 @@ Spree has two permanent, complementary systems for custom data — **metadata fo**Use [Metadata](/developer/customization/metadata)** for external system IDs, tracking attribution, syncing with integrations, or simple write-and-forget data that only backend systems need to read.<Warning>-Product Properties are deprecated and will be removed in Spree 6.0. For new projects, always use Metafields. For existing projects, plan to migrate using the [migration guide](/developer/upgrades/5.1-to-5.2#migrate-to-metafields-or-keep-using-product-properties).+Product Properties are deprecated and will be removed in Spree 6.0. For new projects, always use Metafields. For existing projects, plan to migrate using the [migration guide](/v5/developer/upgrades/5.1-to-5.2#migrate-to-metafields-or-keep-using-product-properties).</Warning>## Related Documentationdiff --git a/docs/developer/core-concepts/orders.mdx b/docs/developer/core-concepts/orders.mdxindex e92daeb4ac..cad555f9fb 100644--- a/docs/developer/core-concepts/orders.mdx+++ b/docs/developer/core-concepts/orders.mdx@@ -1,419 +1,166 @@---title: Orders-description: How Spree models orders — the cart-to-completion lifecycle, checkout state machine, line items, payments, shipments, and order totals.+description: How Spree models orders — a permanent record created by completing a cart, with separate payment and delivery statuses.---## Overview-An order is the central model connecting a customer to their purchase. It collects line items, addresses, shipments, payments, and adjustments into a single transaction that flows through a checkout state machine from cart to completion.+An order is a placed purchase. It's created by completing a [Cart](/developer/core-concepts/carts) and holds its own copy of everything the customer agreed to — items, prices, taxes, discounts and delivery.```mermaiderDiagramOrder ||--o{ LineItem : "has many"- Order ||--o{ Shipment : "has many"+ Order ||--o{ Fulfillment : "has many"Order ||--o{ Payment : "has many"- Order ||--o{ Adjustment : "has many"- Order }o--|| Address : "ship_address"- Order }o--|| Address : "bill_address"- Order }o--|| User : "belongs to"- Order }o--|| Store : "belongs to"- LineItem }o--|| Variant : "belongs to"- Shipment }o--|| StockLocation : "ships from"- Payment }o--|| PaymentMethod : "belongs to"+ Order ||--o{ Return : "has many"+ Order }o--|| Cart : "created from"+ Order }o--|| Customer : "belongs to"Order {string number- string state- string email- string currency- decimal total- string payment_state- string shipment_state- }-- LineItem {- integer quantity- decimal price- }-- Shipment {- string number- string state- string tracking- }-- Payment {- decimal amount- string state+ string payment_status+ string fulfillment_status+ string total+ datetime completed_at}```-**Key relationships:**-- **Line Items** link orders to [Variants](/developer/core-concepts/products#variants) (what was purchased)-- **[Shipments](/developer/core-concepts/shipments)** handle fulfillment from stock locations-- **[Payments](/developer/core-concepts/payments)** track payment attempts and their states-- **[Adjustments](/developer/core-concepts/adjustments)** apply taxes, promotions, and shipping costs-- **[Addresses](/developer/core-concepts/addresses)** store billing and shipping information--## Order Attributes--The API returns these key fields on every order:+## Order attributes| Attribute | Description |-|-----------|-------------|-| `number` | Unique order number (e.g., `R123456789`), shown to customers |+|---|---|+| `id` | Order ID, e.g. `or_86Rf07xd4z` |+| `number` | Order number shown to customers, e.g. `R1001` — sequential by default, [customizable](/developer/how-to/custom-document-numbers) |+| `cart_id` | The cart this order came from || `email` | Customer's email address |-| `currency` | Order currency (e.g., `USD`) |+| `currency` | Order currency, e.g. `USD` || `total_quantity` | Total number of items |+| `payment_status` | See [statuses](#statuses) below |+| `fulfillment_status` | See [statuses](#statuses) below || `item_total` / `display_item_total` | Sum of line item prices || `delivery_total` / `display_delivery_total` | Delivery cost || `tax_total` / `display_tax_total` | Total tax |-| `discount_total` / `display_discount_total` | Total discount from promotions |-| `adjustment_total` / `display_adjustment_total` | Sum of all adjustments (tax + delivery + promos) |-| `total` / `display_total` | Final order total |-| `payment_status` | Payment status (`balance_due`, `paid`, `credit_owed`, `failed`, `void`) |-| `fulfillment_status` | Fulfillment status (`pending`, `ready`, `partial`, `shipped`, `backorder`) |-| `completed_at` | Timestamp when the order was placed |+| `discount_total` / `display_discount_total` | Total discount |+| `total` / `display_total` | Order total |+| `amount_due` / `display_amount_due` | Still outstanding |+| `completed_at` | When the order was placed |-The [`display_*` fields return formatted strings with currency symbols](/api-reference/store-api/monetary-amounts) (e.g., `"$15.99"`).+Every amount comes in two forms: `total` is the raw value (`"135.60"`) and [`display_total` is formatted for the currency](/api-reference/store-api/monetary-amounts) (`"$135.60"`). Render the `display_` one.-## Cart+## Statuses-A cart is simply an order in the `cart` state. Guest carts are [identified by a cart token; authenticated users' carts are linked to their account](/api-reference/store-api/authentication).+An order tracks payment and delivery separately, because they genuinely move at different speeds. An order can be paid but not yet sent, or sent and later partly refunded.-<CodeGroup>+**`payment_status`**-```typescript Store SDK-// Create a cart-const cart = await client.carts.create()-// cart.token => "abc123" (save this for guest checkout)+| Value | Meaning |+|---|---|+| `none` | Nothing paid or authorized yet |+| `authorized` | Money is held but not taken |+| `partially_paid` | Some of the total has been taken |+| `paid` | Fully paid |+| `partially_refunded` | Some money returned |+| `refunded` | Everything returned |+| `overcharged` | More was taken than the order total |+| `voided` | The hold was released without taking money |-// Get existing cart-const cart = await client.carts.get(cartId, { spreeToken: 'xxx' })+**`fulfillment_status`**-// Add an item-const updatedOrder = await client.carts.items.create(cart.id, {- variant_id: 'var_xxx',- quantity: 2,-})+| Value | Meaning |+|---|---|+| `unfulfilled` | Nothing has gone out yet |+| `backorder` | Waiting on stock |+| `partial` | Some of it has gone out |+| `fulfilled` | Everything has gone out |+| `delivered` | The customer has all of it |+| `canceled` | Nothing will be sent |-// Update quantity-await client.carts.items.update(cart.id, 'li_xxx', {- quantity: 3,-})+A canceled parcel is ignored while others are still live, so an order whose second parcel was recalled is described by the first.-// Remove an item-await client.carts.items.delete(cart.id, 'li_xxx')-```+Both are worked out automatically from the order's payments, refunds and fulfillments. You change an order's status by acting on those — taking a payment, sending a parcel, issuing a refund — never by setting the status yourself.-```bash cURL-# Create a cart-curl -X POST 'https://api.mystore.com/api/v3/store/carts' \- -H 'X-Spree-API-Key: pk_xxx'--# Get existing cart-curl 'https://api.mystore.com/api/v3/store/carts/cart_xxx' \- -H 'X-Spree-API-Key: pk_xxx' \- -H 'X-Spree-Token: abc123'+## Reading an order-# Add an item-curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_xxx/items' \- -H 'X-Spree-API-Key: pk_xxx' \- -H 'X-Spree-Token: abc123' \- -H 'Content-Type: application/json' \- -d '{ "variant_id": "var_xxx", "quantity": 2 }'--# Update quantity-curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx/items/li_xxx' \- -H 'X-Spree-API-Key: pk_xxx' \- -H 'X-Spree-Token: abc123' \- -H 'Content-Type: application/json' \- -d '{ "quantity": 3 }'--# Remove an item-curl -X DELETE 'https://api.mystore.com/api/v3/store/carts/cart_xxx/items/li_xxx' \- -H 'X-Spree-API-Key: pk_xxx' \- -H 'X-Spree-Token: abc123'-```--</CodeGroup>--Every item mutation returns the full updated order with recalculated totals.--## Checkout Flow--The checkout is a state machine that advances the order through a series of steps. Each step collects required information before allowing the order to proceed.--<Steps>- <Step title="cart">- Customer has items in their cart. This is the starting state.- </Step>- <Step title="address">- Customer provides shipping and billing addresses.- </Step>- <Step title="delivery">- Customer selects a shipping rate for each shipment.- </Step>- <Step title="payment">- Customer provides payment. Skipped if the order is fully covered by store credit.- </Step>- <Step title="confirm">- Customer reviews and confirms the order.- </Step>- <Step title="complete">- Order is placed. `completed_at` is set and fulfillment begins.- </Step>-</Steps>--If the order doesn't meet the requirements for the next state (e.g., missing address), the API returns an error.+A customer can fetch their own order; guests use the order token they got at checkout.<CodeGroup>```typescript Store SDK-// Set addresses-await client.carts.update(cartId, {- email: '[email protected]',- shipping_address: {- first_name: 'John', last_name: 'Doe',- address1: '123 Main St', city: 'Los Angeles',- country_iso: 'US', state_abbr: 'CA', postal_code: '90001',- phone: '555-0100',- },-})--// Get fulfillments and select a delivery rate-// (the Store API/SDK exposes shipments as `fulfillments`)-const cart = await client.carts.get(cartId)-await client.carts.fulfillments.update(cartId, cart.fulfillments[0].id, {- selected_delivery_rate_id: 'rate_xxx',-})--// Create a payment session (e.g., Stripe)-const session = await client.carts.paymentSessions.create(cartId, {- payment_method_id: 'pm_xxx',-})-// session.external_data.client_secret => use with Stripe.js--// Complete the payment session after provider confirmation-await client.carts.paymentSessions.complete(cartId, session.id)+// A single order+const order = await client.orders.get('or_xxx')-// Complete the order-await client.carts.complete(cartId)+// The signed-in customer's order history+const orders = await client.customers.orders.list({ per_page: 20 })``````bash cURL-# Set addresses-curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx' \- -H 'X-Spree-API-Key: pk_xxx' \- -H 'X-Spree-Token: abc123' \- -H 'Content-Type: application/json' \- -d '{- "email": "[email protected]",- "shipping_address": {- "first_name": "John", "last_name": "Doe",- "address1": "123 Main St", "city": "Los Angeles",- "country_iso": "US", "state_abbr": "CA", "postal_code": "90001",- "phone": "555-0100"- }- }'--# Select a delivery rate-curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx/fulfillments/ful_xxx' \- -H 'X-Spree-API-Key: pk_xxx' \- -H 'X-Spree-Token: abc123' \- -H 'Content-Type: application/json' \- -d '{ "selected_delivery_rate_id": "rate_xxx" }'--# Complete the order-curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_xxx/complete' \+curl 'https://api.mystore.com/api/v3/store/orders/or_xxx' \-H 'X-Spree-API-Key: pk_xxx' \- -H 'X-Spree-Token: abc123'+ -H 'X-Spree-Token: order_token_xxx'```</CodeGroup>-## Coupon Codes+## Managing orders-Apply or remove promotional coupon codes during checkout:--<CodeGroup>--```typescript Store SDK-// Apply a discount code-await client.carts.discountCodes.apply(cartId, 'SAVE20')--// Remove a discount code-await client.carts.discountCodes.remove(cartId, 'SAVE20')-```--```bash cURL-# Apply a discount code-curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_xxx/discount_codes' \- -H 'X-Spree-API-Key: pk_xxx' \- -H 'X-Spree-Token: abc123' \- -H 'Content-Type: application/json' \- -d '{ "code": "SAVE20" }'--# Remove a discount code-curl -X DELETE 'https://api.mystore.com/api/v3/store/carts/cart_xxx/discount_codes/SAVE20' \- -H 'X-Spree-API-Key: pk_xxx' \- -H 'X-Spree-Token: abc123'-```--</CodeGroup>--## Order History--Authenticated customers can view their past orders:--<CodeGroup>--```typescript Store SDK-// List past orders-const { data: orders } = await client.customer.orders.list()--// Get a specific order with details-const order = await client.orders.get('or_xxx', {- expand: ['items', 'fulfillments', 'payments'],-})-```--```typescript Admin SDK-const order = await adminClient.orders.get('or_xxx')-```--```bash cURL-# List past orders-curl 'https://api.mystore.com/api/v3/store/customer/orders' \- -H 'Authorization: Bearer <jwt_token>'--# Get a specific order-curl 'https://api.mystore.com/api/v3/store/orders/or_xxx?expand=items,fulfillments,payments' \- -H 'Authorization: Bearer <jwt_token>'-```--</CodeGroup>--## Managing Orders--Everything above is the **Store API** — the customer's own cart and orders. Back-office order management (listing every order, creating phone/manual orders, capturing payments, cancelling) uses the [Admin API](/api-reference/admin-api/introduction).--### Listing and creating orders--List orders with [Ransack filters and pagination](/api-reference/admin-api/querying) (`state_eq`, `limit`, sorting). A draft order is created in one call; pass line items as `items` (each `{ variant_id, quantity }`):+Back-office work happens through the Admin API.<CodeGroup>```typescript Admin SDK-import { createAdminClient } from '@spree/admin-sdk'--const client = createAdminClient({- baseUrl: 'https://store.example.com',- secretKey: 'sk_xxx',+// Find orders needing attention+const orders = await adminClient.orders.list({+ filter: { payment_status_eq: 'paid', fulfillment_status_eq: 'unfulfilled' },})-// List orders (Ransack filters)-const { data: orders } = await client.orders.list({ state_eq: 'complete', limit: 25 })--// Create a draft order on a customer's behalf-const order = await client.orders.create({- email: '[email protected]',- items: [{ variant_id: 'variant_xxx', quantity: 2 }],- currency: 'USD',+// Cancel an order+await adminClient.orders.cancel('or_xxx', {+ reason: 'customer',+ restock_items: true,+ refund_payments: true,})-```--```bash CLI-spree api get /orders -q state_eq=complete --limit 25-spree api post /orders -d '{- "email": "[email protected]",- "items": [{ "variant_id": "variant_xxx", "quantity": 2 }]-}'-```--</CodeGroup>--### Order state actions-Orders move through their [state machine](#checkout-flow) via dedicated actions rather than raw `state` writes:+// Take an authorized payment+await adminClient.orders.payments.capture('or_xxx', 'pay_xxx')-<CodeGroup>--```typescript Admin SDK-await client.orders.complete('or_xxx') // finalize a draft-await client.orders.cancel('or_xxx', { reason: 'customer' })-await client.orders.approve('or_xxx')-await client.orders.resume('or_xxx')-await client.orders.resendConfirmation('or_xxx')-```--```bash CLI-spree api patch /orders/or_xxx/complete-spree api patch /orders/or_xxx/cancel -d '{"reason": "customer"}'-spree api patch /orders/or_xxx/approve+// Refund against a specific payment+await adminClient.orders.refunds.create('or_xxx', {+ payment_id: 'pay_xxx',+ amount: '25.00',+})```-</CodeGroup>--### Payments and refunds--Capture or void an authorized payment, and issue refunds, through the nested order resources:--<CodeGroup>--```typescript Admin SDK-await client.orders.payments.capture('or_xxx', 'pay_xxx')-await client.orders.payments.void('or_xxx', 'pay_xxx')-await client.orders.refunds.create('or_xxx', { payment_id: 'pay_xxx', amount: '19.99' })-```+```bash cURL+curl 'https://api.mystore.com/api/v3/admin/orders?filter[payment_status_eq]=paid' \+ -H 'X-Spree-API-Key: sk_xxx'-```bash CLI-spree api patch /orders/or_xxx/payments/pay_xxx/capture-spree api post /orders/or_xxx/refunds -d '{"payment_id": "pay_xxx", "amount": "19.99"}'+curl -X PATCH 'https://api.mystore.com/api/v3/admin/orders/or_xxx/cancel' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{ "reason": "customer", "restock_items": true }'```</CodeGroup>-## Line Items--Line items represent individual products in an order. Each line item links to a [Variant](/developer/core-concepts/products#variants) and tracks the quantity and price at the time of purchase.--When a variant is added to an order, the price is locked on the line item. If the variant's price changes later, existing orders are unaffected.--## Adjustments+Canceling records who canceled and why, puts stock back, and settles any payments.-[Adjustments](/developer/core-concepts/adjustments) modify an order's total — promotions decrease it, taxes and shipping increase it. Adjustments can be applied at the order level, the line item level, or the shipment level.+## Orders don't change quietly-## Payment States+A placed order is meant to stay put. Its items and prices are written when the cart is completed and then left alone, so an order keeps saying what the customer actually agreed to — even if a product's price changes the next day.-| State | Description |-|-------|-------------|-| `balance_due` | Payment total is less than the order total |-| `paid` | Payment total equals the order total |-| `credit_owed` | Payment total exceeds the order total (refund pending) |-| `failed` | Most recent payment attempt failed |-| `void` | Order was canceled and payments voided |+Where admin edits are allowed, totals are re-added from the order's existing rows rather than worked out again from scratch. Editing an order must never quietly re-apply today's promotions and hand the customer a different discount than the one they accepted.-## Fulfillment Statuses+## Money on an order-The order's `fulfillment_status` field summarizes the state of all fulfillments (the Store API/SDK exposes shipments as `fulfillments`).+Tax, discounts and fees are kept as separate records, so you can ask what tax was charged without picking through a mixed list. See [Taxes, Discounts & Fees](/developer/core-concepts/taxes-discounts-fees).-| Status | Description |-|--------|-------------|-| `pending` | All fulfillments are pending |-| `ready` | All fulfillments are ready to ship |-| `partial` | At least one fulfillment is shipped, others are not |-| `shipped` | All fulfillments have been shipped |-| `backorder` | Some inventory is on backorder |+## Events-For more details, see [Shipments](/developer/core-concepts/shipments) and [Payments](/developer/core-concepts/payments).+Orders publish [events](/developer/core-concepts/events) — `order.placed`, `order.canceled`, `order.paid` and more — which also reach [webhooks](/developer/core-concepts/webhooks). This is the right way to push orders to another system, trigger fulfillment, or start an email flow.-## Related Documentation+## Related-- [Cart, Checkout & Orders](/developer/sdk/store/cart-checkout) — Store SDK guide for carts, checkout, coupon codes, and order history-- [Payments](/developer/core-concepts/payments) — Payment processing and payment sessions-- [Shipments](/developer/core-concepts/shipments) — Fulfillment and shipping rates-- [Addresses](/developer/core-concepts/addresses) — Billing and shipping addresses-- [Promotions](/developer/core-concepts/promotions) — Discounts and coupon codes-- [Checkout Customization](/developer/customization/checkout) — Customizing the checkout flow-- [Events](/developer/core-concepts/events) — Subscribe to order events (e.g., `order.completed`)+- [Carts](/developer/core-concepts/carts) — shopping and checkout+- [Fulfillments](/developer/core-concepts/fulfillments) — getting items to the customer+- [Returns, Exchanges & Claims](/developer/core-concepts/returns-exchanges-claims) — after the sale+- [Payments](/developer/core-concepts/payments) — payment methods and processingdiff --git a/docs/developer/core-concepts/payments.mdx b/docs/developer/core-concepts/payments.mdxindex f8b5f92f80..1bf4e5ddbd 100644--- a/docs/developer/core-concepts/payments.mdx+++ b/docs/developer/core-concepts/payments.mdx@@ -697,7 +697,7 @@ See [Events](/developer/core-concepts/events) for more details on subscribing to- [Payments (Store SDK)](/developer/sdk/store/payments) - SDK how-to for payment sessions, payments, and setup sessions- [Build a Custom Payment Method](/developer/how-to/custom-payment-method) - Step-by-step guide to creating your own payment gateway integration- [Orders](/developer/core-concepts/orders) - Order management and state machine-- [Checkout Customization](/developer/customization/checkout) - Customizing the checkout flow+- [Checkout Customization](/developer/core-concepts/carts) - Customizing the checkout flow- [Events](/developer/core-concepts/events) - Subscribe to payment events## Key Servicesdiff --git a/docs/developer/core-concepts/promotions.mdx b/docs/developer/core-concepts/promotions.mdxindex 9995bea912..cf2f51ad1f 100644--- a/docs/developer/core-concepts/promotions.mdx+++ b/docs/developer/core-concepts/promotions.mdx@@ -5,23 +5,18 @@ description: Build percentage and fixed-amount discounts, free shipping, BOGO of## Overview-Promotions within Spree are used to provide discounts to orders, offer free shipping, or add items at no extra cost (e.g., free gifts). The promotion system is highly flexible, allowing you to create complex promotional campaigns based on various conditions.--### Promotion Model Diagram+Promotions give money off an order — a percentage off, free shipping, or free items added to the cart. A promotion is a campaign definition: **rules** decide when it applies, **actions** decide what it does. When a promotion applies, its actions write [Discount](/developer/core-concepts/taxes-discounts-fees#discounts) rows on the order.```mermaiderDiagramPromotion {string name- string descriptionstring kindstring code- string pathdatetime starts_atdatetime expires_atinteger usage_limitstring match_policy- boolean advertise}PromotionRule {@@ -31,7 +26,6 @@ erDiagramPromotionAction {string type- integer position}CouponCode {@@ -39,48 +33,33 @@ erDiagramstring state}- OrderPromotion {- integer order_id- integer promotion_id- }-- Adjustment {- decimal amount+ Discount {string label- boolean eligible- string state+ string kind+ string code+ string amount}Promotion ||--o{ PromotionRule : "has many"Promotion ||--o{ PromotionAction : "has many"Promotion ||--o{ CouponCode : "has many"- Promotion ||--o{ OrderPromotion : "has many"- Promotion }o--o{ Store : "available in"- PromotionRule }o--o{ Product : "applies to"- PromotionRule }o--o{ Taxon : "applies to"- PromotionRule }o--o{ User : "applies to"- PromotionAction ||--o{ Adjustment : "creates"- PromotionAction ||--|| Calculator : "has one"- Order ||--o{ OrderPromotion : "has many"- CouponCode }o--o| Order : "used by"+ PromotionAction ||--o{ Discount : "writes"+ Order ||--o{ Discount : "has many"```-**Key relationships:**-- **Promotion** defines the campaign with rules and actions-- **Promotion Rules** determine eligibility conditions (FirstOrder, ItemTotal, Taxon, etc.)-- **Promotion Actions** define what happens when applied (discount, free shipping, free items)-- **Coupon Codes** track usage for code-based promotions-- **[Adjustments](/developer/core-concepts/adjustments)** are created on orders/line items to apply discounts-Promotions can be activated in two ways:-- **Automatic promotions** - Applied automatically when eligibility rules are met (e.g., free shipping on orders over $50)-- **Coupon code promotions** - Applied when a customer enters a valid code during checkout+- **Automatic promotions** — applied on their own when the rules are met (e.g. free shipping on orders over $50)+- **Coupon code promotions** — applied when a customer enters a valid code during checkout++### How discounts are recorded++Each applied promotion becomes one or more Discount rows on the order — on a specific line item or on a fulfillment, never a loose adjustment. Each row keeps a copy of the coupon code and the configured value ("10% off"), so the order still tells the whole story even if the promotion is deleted later.-Promotions consist of two main components:+Two things follow from this design:-- **Rules** - Conditions that must be met for the promotion to apply-- **Actions** - What happens when the promotion is applied (discount, free shipping, etc.)+- **Only winners are stored.** When several promotions compete for the same item, Spree picks the one that saves the customer the most and writes only that one. Losing candidates are recomputed on every cart change, so a promotion that loses today can win tomorrow without any bookkeeping.+- **A discount on the whole order is shared out across the items.** If a customer later returns one item, Spree knows exactly how much of the discount belonged to it.## Promotion Attributes@@ -89,16 +68,15 @@ Promotions consist of two main components:| `name` | The name of the promotion | Summer Sale || `description` | Brief description (max 255 chars) | 20% off all summer items || `kind` | Type: `coupon_code` or `automatic` | `automatic` |-| `starts_at` | When the promotion becomes active | 2025-06-01 00:00:00 |-| `expires_at` | When the promotion expires | 2025-09-01 23:59:59 |+| `starts_at` | When the promotion becomes active | 2026-06-01 00:00:00 |+| `expires_at` | When the promotion expires | 2026-09-01 23:59:59 || `usage_limit` | Max times the promotion can be used | 500 || `match_policy` | How rules are evaluated: `all` or `any` | `all` || `advertise` | Whether to display on storefront | `true` |-| `path` | SEO-friendly URL path | `summer-sale` |### Multi-Code Promotions-For promotions that need unique codes per customer (e.g., influencer campaigns), Spree supports bulk code generation:+For promotions that need unique codes per customer (e.g. influencer campaigns), Spree supports bulk code generation:| Attribute | Description | Example ||-----------|-------------|---------|@@ -106,158 +84,65 @@ For promotions that need unique codes per customer (e.g., influencer campaigns),| `number_of_codes` | How many codes to generate | 1000 || `code_prefix` | Prefix for generated codes | `SUMMER` |-Generated codes follow the pattern `{prefix}{random}`, e.g., `SUMMER22A0F62A230BD919`.+Generated codes follow the pattern `{prefix}{random}`, e.g. `SUMMER22A0F62A230BD919`.## Rules-Rules determine when a promotion is eligible. You can combine multiple rules and configure whether **all** rules must match or **any** rule is sufficient (via `match_policy`).--### FirstOrder--Applies only to a customer's first order. Checks both user account and email address to prevent abuse.--**Use case:** Welcome discount for new customers.--### ItemTotal--Requires the order subtotal to meet minimum and/or maximum thresholds.--**Configuration:**-- `preferred_amount_min` - Minimum order amount (default: 100.00)-- `preferred_operator_min` - Comparison operator: `gt` (greater than) or `gte` (greater than or equal)-- `preferred_amount_max` - Maximum order amount (optional)-- `preferred_operator_max` - Comparison operator: `lt` (less than) or `lte` (less than or equal)--**Use case:** "Free shipping on orders over $50", "10% off orders between $100-$500".--### Product--Requires specific products to be in the order.--**Configuration:**-- `preferred_match_policy`:- - `any` - At least one of the specified products- - `all` - All specified products must be present- - `none` - None of the specified products (exclusion)--**Use case:** "Buy Product A and get 20% off", "Discount excludes sale items".--### Taxon--Requires products from specific categories (taxons) to be in the order.--**Configuration:**-- `preferred_match_policy`: `any` or `all`--The rule automatically includes products in child taxons when a parent taxon is selected.--**Use case:** "20% off Electronics", "Buy from Shoes category get 10% off".--### User--Limits the promotion to specific customer accounts.--**Use case:** Employee discounts, VIP customer promotions.--### UserLoggedIn--Requires the customer to be logged in with an account.--**Use case:** Member-only discounts.--### OneUsePerUser--Ensures each customer can only use the promotion once.--**Use case:** One-time welcome offers, limited redemption campaigns.--### Country--Limits the promotion to orders shipping to a specific country.--**Configuration:**-- `preferred_country_id` or `preferred_country_iso` (ISO 2-letter code)--**Use case:** Regional promotions, country-specific campaigns.--### Currency--Limits the promotion to orders in a specific currency.--**Configuration:**-- `preferred_currency` - Currency code (e.g., "USD", "EUR")--**Use case:** Currency-specific pricing strategies.--### OptionValue--Requires products with specific option values (e.g., size, color) to be in the order.--**Configuration:**-- `preferred_eligible_values` - Array of `Spree::OptionValueVariant` IDs (the option-value↔variant join records the rule matches against the order's variants), not variant IDs--**Use case:** "10% off all red items", "Discount on size XL".--### CustomerGroup--Limits the promotion to customers belonging to specific customer groups.--**Configuration:**-- `preferred_customer_group_ids` - Array of customer group IDs--Customer groups are managed in Admin > Customers > Customer Groups and allow you to segment customers for targeted promotions.--**Use case:** VIP programs, loyalty tiers, wholesale pricing, B2B customer segments.+Rules decide when a promotion is eligible. You can combine multiple rules and configure whether **all** must match or **any** is enough (via `match_policy`).++| Rule | Applies when |+|---|---|+| **FirstOrder** | It's the customer's first order (checked by account and email) |+| **ItemTotal** | The order subtotal is within configured minimum/maximum thresholds |+| **Product** | Specific products are in the order (`any` / `all` / `none` match policy) |+| **Category** | Products from specific categories are in the order — child categories count |+| **OptionValue** | Products with specific option values (size, color) are in the order |+| **User** | The customer is one of the listed accounts |+| **UserLoggedIn** | The customer is logged in |+| **OneUsePerUser** | The customer hasn't used this promotion before |+| **CustomerGroup** | The customer belongs to one of the configured customer groups |+| **Country** | The order ships to a specific country |+| **Currency** | The order is in a specific currency |+| **Channel** | The order was placed through one of the configured [channels](/developer/core-concepts/channels) |+| **Market** | The order belongs to one of the configured [markets](/developer/core-concepts/markets) |++You can also [build your own rules](/developer/how-to/custom-promotion) for business-specific conditions.## Actions-Actions define what happens when a promotion is applied.+Actions define what happens when a promotion applies.### CreateAdjustment-Creates a discount on the entire order total.+A discount on the whole order. The amount is distributed proportionally across the line items — there is no single order-level row, so per-item reporting and partial returns always know their share.-**Default calculator:** `FlatPercentItemTotal` (percentage off order)--**Available calculators:**-- `FlatPercentItemTotal` - Percentage off the order total-- `FlatRate` - Fixed amount off-- `FlexiRate` - First item at one rate, additional items at another-- `TieredFlatRate` - Different rates based on order total tiers-- `TieredPercent` - Different percentages based on order total tiers+**Default calculator:** `FlatPercentItemTotal` (percentage off the order). Also available: `FlatRate`, `FlexiRate`, `TieredFlatRate`, `TieredPercent`.**Use case:** "10% off your order", "$20 off orders over $100".### CreateItemAdjustments-Creates discounts on individual line items. Only applies to items that match the promotion rules (e.g., items in a specific category).--**Default calculator:** `PercentOnLineItem` (percentage off each item)+A discount on individual line items. Only items that match the promotion's rules receive it — if a Category rule says "Electronics", only electronics are discounted.-The action respects rule actionability - if a Taxon rule specifies "Electronics", only electronics items receive the discount.+**Default calculator:** `PercentOnLineItem` (percentage off each item).**Use case:** "15% off shoes", "Buy 2+ shirts get 10% off each".### FreeShipping-Makes all shipments free by creating negative adjustments equal to shipping costs.+Writes a discount on each fulfillment covering its delivery cost. The row is kept even when the cost is zero — its presence is what marks the order as having free shipping.**Use case:** "Free shipping on orders over $75", "Free shipping with code FREESHIP".### CreateLineItems-Automatically adds specified products to the cart when the promotion is eligible.--**Configuration:**-- Map of variant IDs to quantities to add--The action checks stock availability before adding items. Items are not automatically removed if eligibility is lost - customers must remove them manually.+Adds specified products to the cart when the promotion is eligible, checking stock first. Items are not removed automatically if eligibility is lost — customers remove them manually.-**Use case:** "Free gift with purchase", "Buy 2 get 1 free", "Spend $100 get free sample".+**Use case:** "Free gift with purchase", "Spend $100 get a free sample".## Managing Promotions-Create and manage promotions via the [Admin API](/api-reference/admin-api/introduction). Rules and actions can be supplied inline on create — each is a `{ type, preferences }` draft using the rule/action types described above:+Create and manage promotions via the [Admin API](/api-reference/admin-api/introduction). Rules and actions can be supplied inline on create — each is a `{ type, preferences }` draft using the rule and action types described above:<CodeGroup>@@ -314,26 +199,20 @@ spree api patch /promotions/promo_xxx -d '{"expires_at": "2026-09-01T00:00:00Z"}</CodeGroup>-## Coupon Codes--Coupon codes track promotion usage and can be single-use or multi-use.--### Single Code Promotions+The available rule and action types — including any custom ones you register — are discoverable at `/api/v3/admin/promotion_rules/types` and `/api/v3/admin/promotion_actions/types`, together with their preference schemas. The dashboard's promotion editor is built on these endpoints, so custom types show up there without any UI work.-Set the `code` attribute directly on the promotion. The `usage_limit` controls how many times it can be redeemed.+<Note>+Deleting a promotion doesn't disturb the orders that used it. Their discount rows stay, keeping the code and value they were created with — only the link back to the promotion is cleared.+</Note>-### Multi-Code Promotions--For bulk-generated codes, each code tracks its usage state:+## Coupon Codes-| Attribute | Description | Example |-|-----------|-------------|---------|-| `code` | The unique code | `SUMMER22A0F62A230BD919` |-| `state` | Usage state | `unused`, `used` |+Coupon codes track promotion usage and can be single-use or multi-use.-## Applying Coupon Codes via Store API+- **Single code** — set the `code` attribute on the promotion; `usage_limit` controls how many times it can be redeemed.+- **Multi-code** — bulk-generated codes each track their own state (`unused` / `used`).-Customers [apply coupon codes during checkout](/developer/sdk/store/cart-checkout) via the Store API:+Customers apply codes on the cart via the Store API:<CodeGroup>@@ -360,26 +239,22 @@ curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_abc123/discount_co</CodeGroup>-Automatic promotions are applied without any customer action — they are evaluated on every order update.+The returned cart already carries the updated discounts and totals. If the cart doesn't qualify yet — say the code needs a $100 minimum and the cart holds $80 — the code stays on the cart and the discount activates on its own the moment the cart qualifies.-## Promotion Flow+Automatic promotions need no customer action at all — they are evaluated on every cart change.-How promotions are evaluated and applied:+## Promotion Flow-1. **Order Update** — When an order is updated, the system checks all eligible promotions-2. **Eligibility Check** — For each promotion:- - Check if within `starts_at` and `expires_at` range- - Check if under `usage_limit`- - Evaluate all rules based on `match_policy` (all or any)-3. **Action Execution** — If eligible, each action is applied-4. **Tracking** — Applied promotions are recorded on the order-5. **Re-evaluation** — Eligibility is re-checked on every order update; adjustments from ineligible promotions are removed+1. **Cart change** — every change to a cart (item added, address entered, code applied) triggers a recalculation+2. **Eligibility** — each connected promotion is checked: active dates, usage limits, then rules per `match_policy`+3. **Competition** — candidate discounts are computed for every eligible promotion; per item, per fulfillment, and order-wide, the largest saving wins+4. **Persistence** — winning discounts are written as rows; anything stale from the previous pass is removed; tax is then estimated on the discounted amounts+5. **Placement** — once the order is placed, its discount rows are frozen; usage counts are recorded against the promotion## Related Documentation-- [Build Custom Promotion Rules & Actions](/developer/how-to/custom-promotion) - Step-by-step guide to creating custom rules and actions-- [Calculators](/developer/core-concepts/calculators) - Learn about promotion calculators-- [Orders](/developer/core-concepts/orders) - Understanding order processing-- [Customization Quickstart](/developer/customization/quickstart) - Overview of customization options-- [Admin SDK Resources](/developer/sdk/admin/resources) - The `client.promotions.*` resource-client pattern used in the examples above-- [Spree CLI Admin API](/developer/cli/admin-api) - The `spree api` command reference for the CLI examples above+- [Taxes, Discounts & Fees](/developer/core-concepts/taxes-discounts-fees) — the Discount rows promotions write, and manual discounts+- [Build Custom Promotion Rules & Actions](/developer/how-to/custom-promotion) — step-by-step guide to custom rules, actions and adjusters+- [Calculators](/developer/core-concepts/calculators) — promotion calculators+- [Carts](/developer/core-concepts/carts) — the cart lifecycle promotions act on+- [Admin SDK Resources](/developer/sdk/admin/resources) — the `client.promotions.*` resource-client pattern used abovediff --git a/docs/v6/developer/core-concepts/returns-exchanges-claims.mdx b/docs/developer/core-concepts/returns-exchanges-claims.mdxsimilarity index 90%rename from docs/v6/developer/core-concepts/returns-exchanges-claims.mdxrename to docs/developer/core-concepts/returns-exchanges-claims.mdxindex 7536bf9cc5..60f89c2f6f 100644--- a/docs/v6/developer/core-concepts/returns-exchanges-claims.mdx+++ b/docs/developer/core-concepts/returns-exchanges-claims.mdx@@ -132,7 +132,7 @@ await adminClient.orders.claims.resolve('or_xxx', 'clm_xxx', {})```-A replacement creates a new [fulfillment](/v6/developer/core-concepts/fulfillments) on the original order, so the customer doesn't have to place a second one.+A replacement creates a new [fulfillment](/developer/core-concepts/fulfillments) on the original order, so the customer doesn't have to place a second one.## Exchanges@@ -162,16 +162,16 @@ const claims = await adminClient.claims.list({Spree ships no built-in return window. Whether a customer may open a return is store policy, and it's checked when the return is created — so you can hold customers to a 30-day window while letting staff make an exception for a good customer, and vary the rule by market where local law requires it.-Set the return window per market, or express a more specific rule in your own application. See [Configuration](/v6/developer/customization/configuration) and [Services & Workflows](/developer/customization/workflows).+Set the return window per market, or express a more specific rule in your own application. See [Configuration](/developer/customization/configuration) and [Services & Workflows](/developer/customization/workflows).## EventsEach step publishes an [event](/developer/core-concepts/events) — `return.received`, `return.refunded`, `exchange.fulfilled`, `claim.resolved` — which also reach [webhooks](/developer/core-concepts/webhooks).-Returns and claims also update the order's [payment status](/v6/developer/core-concepts/orders#statuses), so a refunded order reflects it without any manual bookkeeping.+Returns and claims also update the order's [payment status](/developer/core-concepts/orders#statuses), so a refunded order reflects it without any manual bookkeeping.## Related-- [Orders](/v6/developer/core-concepts/orders) — payment status after refunds-- [Fulfillments](/v6/developer/core-concepts/fulfillments) — replacement deliveries+- [Orders](/developer/core-concepts/orders) — payment status after refunds+- [Fulfillments](/developer/core-concepts/fulfillments) — replacement deliveries- [Inventory](/developer/core-concepts/inventory) — putting returned goods back in stockdiff --git a/docs/developer/core-concepts/store-credits-gift-cards.mdx b/docs/developer/core-concepts/store-credits-gift-cards.mdxindex 8d2dd0b566..0cbe7e7405 100644--- a/docs/developer/core-concepts/store-credits-gift-cards.mdx+++ b/docs/developer/core-concepts/store-credits-gift-cards.mdx@@ -179,7 +179,7 @@ erDiagramGiftCard {string code- string state+ string statusdecimal amountdecimal amount_useddecimal amount_authorized@@ -204,28 +204,26 @@ erDiagram| `code` | Unique redemption code | `abc1234def` || `amount` | Total gift card value | `50.00` || `amount_used` | Amount already redeemed | `0.00` |-| `state` | Current state | `active` |+| `status` | Current status | `active` || `currency` | Currency code | `USD` || `expires_at` | Optional expiration date | `2025-12-31` |-### Gift Card States+### Gift Card Statuses-```mermaid-stateDiagram-v2- [*] --> active: Created- active --> partially_redeemed: Partial redemption- active --> redeemed: Full redemption- active --> canceled: Admin cancels- partially_redeemed --> redeemed: Remaining redeemed- partially_redeemed --> partially_redeemed: Another partial redemption-```+| Status | Description | How it gets there |+|-------|-------------|-------------------|+| `active` | Available for redemption | The status a card is created with |+| `partially_redeemed` | Some value has been redeemed | `Spree::GiftCards::Redeem`, when a balance remains |+| `redeemed` | Fully redeemed | `Spree::GiftCards::Redeem`, when nothing is left |+| `canceled` | Voided, and no longer spendable | `Spree::GiftCards::Cancel` |-| State | Description |-|-------|-------------|-| `active` | Available for redemption |-| `partially_redeemed` | Some value has been redeemed |-| `redeemed` | Fully redeemed |-| `canceled` | Canceled by admin |+Redemption does not need the caller to choose: `Spree::GiftCards::Redeem`+looks at what is left on the card and marks it partially or fully redeemed+accordingly. A card can be partially redeemed more than once, and each spend+publishes its own event.++Cancelling is refused once a card has been spent against, so cancellation can+never take back value a customer has already used.<Note>Gift cards can also be `expired` if `expires_at` date has passed and the card hasn't been fully redeemed.diff --git a/docs/developer/core-concepts/stores.mdx b/docs/developer/core-concepts/stores.mdxindex 82263234a2..0819be2e63 100644--- a/docs/developer/core-concepts/stores.mdx+++ b/docs/developer/core-concepts/stores.mdx@@ -76,7 +76,7 @@ Each store owns its own resources. Products, orders, channels, markets, and taxo| [**Products**](/developer/core-concepts/products) | A product belongs to one store. Its visibility across channels is controlled by [publications](/developer/core-concepts/channels#publishing-products-on-channels). || [**Categories**](/developer/core-concepts/products#categories) | A category belongs to one store || [**Payment Methods**](/developer/core-concepts/payments) | A payment method belongs to one store |-| [**Shipping Methods**](/developer/core-concepts/shipments) | A shipping method belongs to one store |+| [**Shipping Methods**](/developer/core-concepts/fulfillments) | A shipping method belongs to one store || [**Promotions**](/developer/core-concepts/promotions) | A promotion belongs to one store |## Running Multiple Storefrontsdiff --git a/docs/v6/developer/core-concepts/taxes-discounts-fees.mdx b/docs/developer/core-concepts/taxes-discounts-fees.mdxsimilarity index 93%rename from docs/v6/developer/core-concepts/taxes-discounts-fees.mdxrename to docs/developer/core-concepts/taxes-discounts-fees.mdxindex 8572d8bfc7..a52eeddf19 100644--- a/docs/v6/developer/core-concepts/taxes-discounts-fees.mdx+++ b/docs/developer/core-concepts/taxes-discounts-fees.mdx@@ -111,7 +111,7 @@ You never create tax lines yourself. They're written whenever the order total is| `promotion_id` | The promotion it came from || `line_item_id` / `fulfillment_id` | What it reduced |-Most discounts come from [Promotions](/v6/developer/core-concepts/promotions) — a customer applies a code and the rows appear. A **manual** discount is one an admin adds directly, for a goodwill gesture or a price match:+Most discounts come from [Promotions](/developer/core-concepts/promotions) — a customer applies a code and the rows appear. A **manual** discount is one an admin adds directly, for a goodwill gesture or a price match:<CodeGroup>@@ -175,7 +175,7 @@ A duty also keeps a copy of what it was calculated from — the HS code, the couEach row points at exactly the thing it applies to:-- **Tax lines** → a line item, a [fulfillment](/v6/developer/core-concepts/fulfillments), or a fee, so item tax and delivery tax stay separately visible+- **Tax lines** → a line item, a [fulfillment](/developer/core-concepts/fulfillments), or a fee, so item tax and delivery tax stay separately visible- **Discounts** → a line item or a fulfillment- **Fees** → a line item, a fulfillment, or the order itself@@ -200,6 +200,6 @@ Once an order is placed, the rows stop being regenerated. Editing a placed order## Related- [Taxes](/developer/core-concepts/taxes) — how tax is worked out-- [Promotions](/v6/developer/core-concepts/promotions) — where most discounts come from-- [Fulfillments](/v6/developer/core-concepts/fulfillments) — delivery charges-- [Orders](/v6/developer/core-concepts/orders) — order totals and statuses+- [Promotions](/developer/core-concepts/promotions) — where most discounts come from+- [Fulfillments](/developer/core-concepts/fulfillments) — delivery charges+- [Orders](/developer/core-concepts/orders) — order totals and statusesdiff --git a/docs/developer/core-concepts/taxes.mdx b/docs/developer/core-concepts/taxes.mdxindex 1cfac2fa64..e4ead19eb9 100644--- a/docs/developer/core-concepts/taxes.mdx+++ b/docs/developer/core-concepts/taxes.mdx@@ -37,7 +37,7 @@ erDiagram- **Tax Category** groups products for tax purposes (e.g., "Clothing", "Food", "Digital")- **Tax Rate** defines the percentage and rules for a Tax Category within a [Zone](/developer/core-concepts/addresses#zones)- **Zone** defines geographic regions (countries or states) where taxes apply-- **[Adjustments](/developer/core-concepts/adjustments)** are created on orders/line items to apply taxes+- **[Adjustments](/developer/core-concepts/taxes-discounts-fees)** are created on orders/line items to apply taxes## Tax Categories@@ -131,7 +131,7 @@ During checkout, taxes are calculated based on the shipping address:1. The customer's shipping address determines their [Zone](/developer/core-concepts/addresses#zones)2. Spree finds matching tax rates for that zone and the product's tax category-3. Tax [Adjustments](/developer/core-concepts/adjustments) are created on line items+3. Tax [Adjustments](/developer/core-concepts/taxes-discounts-fees) are created on line items4. The order total is updated<Note>@@ -164,6 +164,6 @@ Tax categories and rates are managed in the Admin Panel under **Settings → Tax- [Markets](/developer/core-concepts/markets) — Tax-inclusive pricing per market- [Addresses](/developer/core-concepts/addresses) — Zones and address-based taxation-- [Adjustments](/developer/core-concepts/adjustments) — Tax adjustments+- [Adjustments](/developer/core-concepts/taxes-discounts-fees) — Tax adjustments- [Orders](/developer/core-concepts/orders) — How taxes affect order totals- [Avalara integration](/integrations/tax/avalara) — Automated tax calculation for complex jurisdictionsdiff --git a/docs/developer/create-spree-app/quickstart.mdx b/docs/developer/create-spree-app/quickstart.mdxindex ce33351491..b53eba9eb2 100644--- a/docs/developer/create-spree-app/quickstart.mdx+++ b/docs/developer/create-spree-app/quickstart.mdx@@ -1,6 +1,6 @@---title: "create-spree-app"-sidebarTitle: Overview+sidebarTitle: create-spree-appdescription: "Scaffold a new Spree Commerce project with a single command — bootstraps a full Rails backend, Docker dev stack, and the @spree/cli for customization."---diff --git a/docs/developer/customization/api.mdx b/docs/developer/customization/api.mdxindex ca01659a22..26af88ac44 100644--- a/docs/developer/customization/api.mdx+++ b/docs/developer/customization/api.mdx@@ -5,7 +5,7 @@ description: Add new Store API endpoints, customize existing JSON responses withBefore you start customizing Spree API endpoints, make sure you reviewed all existing API endpoints in the [Spree API docs](/api-reference/admin-api/endpoints).-For a step-by-step walkthrough of adding a complete new resource (model, serializer, controller, routes), see the [API tutorial](/developer/tutorial/api).+For a step-by-step walkthrough of adding a complete new resource (model, serializer, controller, routes), see the [API tutorial](/developer/tutorial/admin-api).## Customizing JSON Responses@@ -35,7 +35,7 @@ Restart the server and the Product API will include your new attribute.### Adding an Association-Let's say you've created a `Spree::Brand` model that belongs to `Product` (see the [tutorial](/developer/tutorial/api) for the full example).+Let's say you've created a `Spree::Brand` model that belongs to `Product` (see the [tutorial](/developer/tutorial/admin-api) for the full example).Create a serializer for the new model:@@ -173,20 +173,49 @@ end### Permitted Attributes-For endpoints that accept writes (create/update), add your attributes:+For endpoints that accept writes (create/update), declare the attributes in your+controller:-```ruby config/initializers/spree.rb-Spree::PermittedAttributes.brand_attributes = [:name, :slug, :description, :logo]+```ruby+def resource_permitted_attributes+ [:name, :slug, :description, :logo]+end```-Or override `permitted_params` in the controller:+Entries are `params.permit` fragments, so collections and nested structures use+the shapes you would pass there directly — `[:name, { region_ids: [] }]`.-```ruby-def permitted_params- params.permit(:name, :slug, :description, :logo)-end+<Note>+ Declare `resource_permitted_attributes`, not `permitted_attributes`. The+ latter is what appends extension-contributed attributes to your list, so+ overriding it replaces them.+</Note>++### Adding an Attribute to a Core Resource++To make a new column writable on a Spree model without decorating the+controllers that write it, append to the model's permitted attributes:++```ruby config/initializers/spree.rb+Spree::Product.additional_permitted_attributes += [:brand_id]```+Standard resource endpoints append these to their own allowlist, so one+declaration covers the model's create and update endpoints.++Use `+=`, never `=` — assigning replaces what another extension added — and+declare only attributes of your own, since redeclaring a key the controller+already permits replaces its filter rather than widening it.++<Note>+ For merchant-managed data, prefer [Custom Fields](/developer/core-concepts/metafields),+ which need no code and are filterable and sortable. This is for extensions+ that add real database columns.+</Note>++Two endpoints deliberately ignore this hook because their parameters are+authorization data rather than resource data: API keys and invitations.+## Consuming Custom Endpoints with the SDK-See the [SDK tutorial](/developer/tutorial/sdk) for how to call custom endpoints from TypeScript and extend the generated types.+See the [SDK tutorial](/developer/tutorial/storefront) for how to call custom endpoints from TypeScript and extend the generated types.diff --git a/docs/developer/customization/configuration.mdx b/docs/developer/customization/configuration.mdxindex 5053223d03..93a76e665c 100644--- a/docs/developer/customization/configuration.mdx+++ b/docs/developer/customization/configuration.mdx@@ -1,57 +1,229 @@----title: "Configuration"+title: Configuration+description: Every global Spree setting that is actually read by Spree 6 — grouped by area, with defaults and what each one changes.----Here is a list of all the configuration options that are available in Spree.-- | Configuration Key | Description | Default Value |- |------------------------------------|-------------------------------------------------------------------------------------------------------|---------------------|- | `allow_checkout_on_gateway_error` | Continues the checkout process even if the payment gateway error failed. | `false` |- | `address_requires_phone` | Determines whether a phone number is required for Addresses. | `false` |- | `alternative_shipping_phone` | Determines if an alternative phone number should be present for the shipping address on the checkout page. | `false` |- | `always_include_confirm_step` | Determines if the confirmation step is always included in the checkout process, regardless of the payment method. | `false` |- | `auto_capture` | Depending on whether or not Spree is configured to "auto capture" the credit card, either a purchase or an authorize operation will be performed on the card (via the current credit card gateway). | `true` |- | `auto_capture_on_dispatch` | Captures payment for each shipment in Shipment#after_ship callback, and makes Shipment.ready when payment authorized. | `false` |- | `company` | Determines whether or not a field for "Company" displays on the address form. | `false` |- | `credit_to_new_allocation` | Determines if a new allocation is created anytime store credit is added. If not set, it will update the store credit's amount in place. | `false` |- | `disable_sku_validation` | Determines if the built-in SKU uniqueness validation is disabled. | `false` |- | `disable_store_presence_validation` | Determines if Store presence validation for Products and Payment Methods is disabled. | `false` |- | `expedited_exchanges` | Determines if an exchange shipment is kicked off upon return authorization save. Requires payment profiles to be supported on your gateway and a configured delayed job handler. | `false` |- | `expedited_exchanges_days_window` | The number of days the customer has to return their item after the expedited exchange is shipped to avoid being charged. | `14` |- | `restock_inventory` | Determines if inventory should be restocked when an order is canceled or returned | `true` |- | `return_eligibility_number_of_days` | The number of days after purchase within which a return can be initiated. | `365` |- | `show_products_without_price` | Determines if products without a price are shown in the storefront and Storefront API | `false` |- | `tax_using_ship_address` | Determines if tax information should be based on shipping address, rather than the billing address. | `true` |- | `track_inventory_levels` | Determines if inventory levels should be tracked when products are purchased at checkout. This option causes new `InventoryUnit` objects to be created when a product is bought. | `true` |--## Spree Initializer--To change values for these preferences, you need to edit your `config/initializers/spree.rb` file.--For example, to disable the `expedited_exchanges` feature, you would add the following line:+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.-```ruby+```ruby config/initializers/spree.rbSpree.config do |config|- config.expedited_exchanges = false+ config.minimum_password_length = 10+ config.allow_empty_price_amount = trueend```<Note>- Remember to restart your Rails server after making changes to the `config/initializers/spree.rb` file.+Restart your Rails server after editing the initializer.</Note>-## Accessing Configuration+## 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.++| Setting | Environment variable | What it configures |+|---|---|---|+| `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`. |++This page lists only settings Spree 6 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.-To access these preferences in your application, you can use the `Spree::Config` module. For example, to access the `expedited_exchanges` preference, you can do the following:+They were global before Spree 6. The global versions still exist for one release but are no longer read, so setting one in the initializer changes nothing — run `bin/rake spree:store_settings:backfill_from_config` during the upgrade to copy your values onto every store.```ruby-Spree::Config.expedited_exchanges+store = Spree::Current.store+store.preferred_capture_method # => "checkout"+store.update!(preferred_track_inventory_levels: false)```-This will return the current value of the `expedited_exchanges` preference. You can also set the value of a preference using the `Spree::Config` module. For example, to set the `expedited_exchanges` preference to `true`, you can do the following:+### 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-Spree::Config.expedited_exchanges = true+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"```-This will set the `expedited_exchanges` preference to `true` for the current process. After restarting the Rails server, the preference will return to the default value or the one set in the initializer.+Before Spree 6 this was two separate booleans, `auto_capture` and `auto_capture_on_dispatch`, which could contradict each other. Two upgrade tasks carry existing installs 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.++## Checkout and payments++| Setting | 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. |++## Carts and stock reservations++| Setting | 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. |++## Products and pricing++| Setting | 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. |++## Addresses++| Setting | Default | What it does |+|---|---|---|+| `geocode_addresses` | `true` | Looks up latitude and longitude for saved addresses. |++## Media++| Setting | 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. |++## Promotions and gift cards++| Setting | 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. |++## Accounts and passwords++| Setting | 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. |++## Imports and events++| Setting | 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++API settings live on their own configuration object:++```ruby config/initializers/spree.rb+Spree::Api::Config.jwt_expiration = 1800+```++### Authentication++| Setting | 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. |++### Rate limits++| Setting | 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 |+|---|---|---|+| `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 6 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 in Spree 6, 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 removed in Spree 6++These were deprecated in Spree 5 and 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. |++## Related++- [Model preferences](/developer/customization/model-preferences) — per-record settings+- [Services & Workflows](/developer/customization/workflows) — changing behavior rather than settingsdiff --git a/docs/developer/customization/decorators.mdx b/docs/developer/customization/decorators.mdxindex 2321ad236b..9eb78d0845 100644--- a/docs/developer/customization/decorators.mdx+++ b/docs/developer/customization/decorators.mdx@@ -9,9 +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/admin/navigation)** - For adding menu items without controller decorators- - **[Admin Partials](/developer/admin/extending-ui)** - For extending admin UI without view decorators- - **[Admin Tables](/developer/admin/tables)** - For customizing admin list views+ - **[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</Warning>@@ -25,8 +25,8 @@ 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/admin/navigation) |-| Add section to admin form | View decorator/override | [Admin Partials injection](/developer/admin/extending-ui) |+| 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 association to core model | - | Decorator (still appropriate) || Add validation to core model | - | Decorator (still appropriate) |@@ -560,7 +560,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/admin/navigation) - Extend admin menu without decorators-- [Admin Partials](/developer/admin/extending-ui) - Extend admin UI without view decorators-- [Extending Core Models Tutorial](/developer/tutorial/extending-models) - Step-by-step guide to connecting custom models with Spree core+- [Admin Navigation](/developer/dashboard/customization/navigation) - Extend admin menu without decorators+- [Admin Partials](/developer/dashboard/customization/quickstart) - Extend admin UI without view decorators+- [Extending Core Models Tutorial](/developer/tutorial/model) - Step-by-step guide to connecting custom models with Spree core- [Customization Overview](/developer/customization/quickstart) - General customization patternsdiff --git a/docs/developer/customization/permissions.mdx b/docs/developer/customization/permissions.mdxindex 0b85f53590..2dafadb918 100644--- a/docs/developer/customization/permissions.mdx+++ b/docs/developer/customization/permissions.mdx@@ -1,267 +1,70 @@---title: Permissions+description: The permission catalog, staff roles, and how extensions register their own permissions.----Spree uses [CanCanCan](https://github.com/CanCanCommunity/cancancan) for authorization. The permission system allows you to define granular access control for different user roles.+Staff roles and their permissions are managed as data — in the dashboard under **Settings → Roles**, through the Admin API (`/api/v3/admin/roles`), or in seeds. There is nothing to configure in Ruby for day-to-day permission management. This page covers what extension and host-application developers can plug into.-## Permission Sets (Recommended)+## The permission catalog-Permission Sets provide a clean, modular way to manage permissions. Each permission set is a reusable group of permissions that can be assigned to roles.+Every grantable capability is a flat key of the form `read_<resource>` or `write_<resource>` — the same vocabulary secret API keys use as scopes. `write_*` implies the matching `read_*`. Discover the catalog at runtime with `GET /api/v3/admin/permissions`; the role editor and the API-key scope picker are both rendered from it.-### How It Works+Keys are per resource, not per action. The money-adjacent areas (`payments`, `refunds`, `gift_cards`, `store_credits`) are separate resources from `orders`, so "view orders but don't refund" needs no special casing.-1. **Roles** - Determine which permission sets govern a user's access (e.g., `admin`, `customer_service`)-2. **Permission Sets** - Contain the logic defining what actions users can perform on resources-3. **Role Configuration** - Associates roles with their corresponding permission sets--### Configuring Roles--In your `config/initializers/spree.rb`, configure which permission sets are assigned to each role:--```ruby-Rails.application.config.after_initialize do- # Default permissions for all users (guests and logged-in customers)- Spree.permissions.assign(:default, [Spree::PermissionSets::DefaultCustomer])-- # Full admin access- Spree.permissions.assign(:admin, [Spree::PermissionSets::SuperUser])-- # Custom role with specific permissions- Spree.permissions.assign(:customer_service, [- Spree::PermissionSets::DashboardDisplay,- Spree::PermissionSets::OrderManagement,- Spree::PermissionSets::UserDisplay- ])-- # Merchandiser role for product management- Spree.permissions.assign(:merchandiser, [- Spree::PermissionSets::DashboardDisplay,- Spree::PermissionSets::ProductManagement,- Spree::PermissionSets::StockManagement- ])-end-```--### Built-in Permission Sets--| Permission Set | Description |-|---------------|-------------|-| `SuperUser` | Full admin access with safety restrictions |-| `DefaultCustomer` | Basic storefront permissions (browse, checkout, manage own account) |-| `DashboardDisplay` | View admin dashboard |-| `OrderDisplay` | Read-only access to orders |-| `OrderManagement` | Full order management (view, edit, refund, etc.) |-| `ProductDisplay` | Read-only access to products and catalog |-| `ProductManagement` | Full catalog management (products, variants, taxonomies) |-| `UserDisplay` | Read-only access to users |-| `UserManagement` | Full user management |-| `StockDisplay` | Read-only access to inventory |-| `StockManagement` | Full inventory management |-| `PromotionManagement` | Manage promotions and coupon codes |-| `ConfigurationManagement` | Manage store settings, shipping, taxes, etc. |-| `RoleManagement` | Manage roles (except the protected admin role) |--### Creating Custom Permission Sets--Create a new permission set in `app/models/spree/permission_sets/`:--```ruby-# app/models/spree/permission_sets/warehouse_management.rb-module Spree- module PermissionSets- class WarehouseManagement < Base- def activate!- can :manage, Spree::StockItem- can :manage, Spree::StockLocation- can :manage, Spree::StockMovement- can :manage, Spree::Shipment- can [:read, :admin], Spree::Order- end- end- end-end-```--Then assign it to a role:--```ruby-Spree.permissions.assign(:warehouse_staff, [- Spree::PermissionSets::DashboardDisplay,- Spree::PermissionSets::WarehouseManagement-])-```--### Permission Set API--Within a permission set, you have access to:--- `can(action, subject, conditions = {})` - Grant permission-- `cannot(action, subject, conditions = {})` - Deny permission-- `can?(action, subject)` - Check if permission exists-- `user` - The current user-- `store` - The current store (for multi-store setups)--```ruby-module Spree- module PermissionSets- class OrderManagementForOwnOrders < Base- def activate!- # Users can only manage orders they created- can :manage, Spree::Order, created_by_id: user.id-- # But cannot cancel any order- cannot :cancel, Spree::Order-- # Unless it's cancellable- can :cancel, Spree::Order, &:allow_cancel?- end- end- end-end-```--### Managing Permission Configuration+Roles as code is plain ActiveRecord:```ruby-# Assign permission sets to a role-Spree.permissions.assign(:customer_service, [- Spree::PermissionSets::OrderDisplay,- Spree::PermissionSets::UserManagement-])--# Add more permission sets to an existing role-Spree.permissions.assign(:customer_service, [- Spree::PermissionSets::StockDisplay-])--# Clear all permission sets from a role-Spree.permissions.clear(:customer_service)--# Check what permission sets a role has-Spree.permissions.permission_sets_for(:customer_service)-# => [Spree::PermissionSets::OrderDisplay, ...]--# Check if a role is configured-Spree.permissions.role_configured?(:customer_service)-# => true+# db/seeds.rb+Spree::Role.find_or_create_by!(name: 'support')+ .update!(permissions: %w[read_orders read_customers], description: 'Read-only support')```-## Users and Roles+A role with `mutable: false` (set from seeds or the console) renders read-only in the dashboard — for roles the application does not want store staff to edit. The `admin` role is always protected.-Spree comes with an `admin` role by default. You can create more roles in the Admin Panel or via Rails console:+## Registering extension permissions-```ruby-Spree::Role.find_or_create_by(name: 'customer_service')-Spree::Role.find_or_create_by(name: 'merchandiser')-Spree::Role.find_or_create_by(name: 'warehouse_staff')-```--Assign a role to a user:+Register your models as a catalog resource once; the keys appear in the role editor and become mintable API-key scopes with no further wiring:```ruby-user = Spree.user_class.find_by(email: '[email protected]')-role = Spree::Role.find_by(name: 'customer_service')-user.spree_roles << role+# in your engine's initializer+Spree.permissions.register_resource(:reviews, group: :catalog, subjects: -> {+ [SpreeReviews::Review]+})```-### Default Role Behavior+- `group` places the row in the permission pickers (`:orders`, `:catalog`, `:marketing`, `:customers`, `:settings`, `:access`, `:analytics` — or your own).+- `subjects` is a lambda returning the CanCanCan subjects the keys grant; it resolves lazily, so load order does not matter.+- Pass `write: false` for read-only resources.-- Users with **no roles assigned** automatically get the `:default` role permissions-- No `RoleUser` records are created for regular customers-- Only users with special permissions need explicit role assignments+Localize the labels in your engine's locale file under `spree.permissions_catalog.resources.<name>` (`label` and `description`), and declare the same resource on your admin controllers with `scoped_resource :reviews`.-## Legacy Approach: Custom Ability Classes+## Beyond the catalog-<Note>-The permission sets approach above is recommended for new projects. The legacy approach below is supported for backward compatibility.-</Note>+The catalog is deliberately flat: it answers "may this role touch this kind of record", and that is the whole grant vocabulary. Two rules that do *not* belong in it:-### Adding Custom Permissions via Decorator--Create a new ability class in `app/models/customer_service_ability.rb`:--```ruby-class CustomerServiceAbility- include CanCan::Ability-- def initialize(user)- if user.respond_to?(:has_spree_role?) && user.has_spree_role?('customer_service')- can :manage, Spree::Order- end- end-end-```--Register it via a decorator in `app/models/spree/ability_decorator.rb`:--```ruby-module Spree- module AbilityDecorator- def abilities_to_register- [CustomerServiceAbility]- end- end-- Ability.prepend(AbilityDecorator)-end-```--### Replacing the Ability Class--You can replace the entire ability class via [Dependencies](/developer/customization/dependencies):+- **Record-state rules** ("a completed order cannot be deleted") live on models and workflows, so they bind every caller — including secret API keys, which never consult CanCanCan.+- **Row-level restrictions** (a support agent limited to one market) are not expressible as keys. Replace the ability class outright:```ruby# config/initializers/spree.rb-Spree::Dependencies.ability_class = 'CustomAbility'+Spree::Dependencies.ability_class = 'MyApp::Ability'``````ruby-# app/models/custom_ability.rb-class CustomAbility < Spree::Ability+# app/models/my_app/ability.rb+class MyApp::Ability < Spree::Abilitydef initialize(user, options = {})- alias_cancan_delete_action-- @user = user || Spree.user_class.new- @store = options[:store] || Spree::Current.store-- if @user.respond_to?(:has_spree_role?) && @user.has_spree_role?('admin')- apply_admin_permissions(@user, options)- elsif @user.respond_to?(:has_spree_role?) && @user.has_spree_role?(:customer_service)- apply_customer_service_permissions(@user)- else- apply_user_permissions(@user, options)- end+ super+ return unless user.respond_to?(:market_id) && user.market_id- protect_admin_role- end-- protected-- def apply_customer_service_permissions(user)- can :manage, Spree::Order- can [:read, :admin], Spree.user_class+ cannot :manage, Spree::Order+ can [:read, :admin], Spree::Order, market_id: user.market_idendend```-## CanCanCan Reference--Spree's permission system is built on CanCanCan. Key concepts:+## How enforcement works-- `can :action, Subject` - Grant permission-- `can :manage, Subject` - Grant all actions (create, read, update, destroy)-- `cannot :action, Subject` - Explicitly deny permission-- `can :action, Subject, conditions` - Conditional permission--```ruby-# Examples-can :read, Spree::Product # Can read any product-can :manage, Spree::Order, user_id: user.id # Can manage own orders-can :update, Spree::Order do |order| # Block conditions- order.user == user && !order.completed?-end-cannot :destroy, Spree::Order # Cannot destroy any order-can :destroy, Spree::Order, &:can_be_deleted? # Unless it's deletable-```+Every Admin API controller declares its resource (`scoped_resource :orders`). Each request checks the principal's keys — a staff member's role permissions on the current store, or a secret key's scopes — against `read_<resource>` or `write_<resource>` for the action. A missing key produces a 403 naming it in `details.required_permission`. Behind that gate, keys compile to CanCanCan rules for record-level concerns, and `GET /api/v3/admin/me` returns both the rule dump the dashboard mirrors and `permission_keys`, the flat key list.-See the [CanCanCan documentation](https://github.com/CanCanCommunity/cancancan) for more details.+Storefront customers are not part of this system — customer authorization is ownership, enforced by the Store API's scoped lookups, with nothing to configure. The one swappable piece is `Spree::Storefront::AccessPolicy` (via `Spree::Dependencies.storefront_access_policy_class`): a generic `readable?` / `writable?` / `scope` protocol that defaults to "the caller owns the record", with carts and orders adding guest-token access. Replace it only when access must widen beyond the owner, such as company accounts sharing purchases or wishlists.diff --git a/docs/developer/customization/quickstart.mdx b/docs/developer/customization/quickstart.mdxindex d23da7806a..b90645b93a 100644--- a/docs/developer/customization/quickstart.mdx+++ b/docs/developer/customization/quickstart.mdx@@ -1,188 +1,217 @@---title: Quickstartog:title: Spree Customization Quickstart-description: Recommended ways to customize Spree — store settings, configuration, events, webhooks, dependencies, admin extensions, and decorators as a last resort.+description: Recommended ways to customize the Spree 6 backend — configuration, workflow hooks, events, checkout steps, providers, dependencies, and decorators as a last resort.----Spree is a flexible platform allowing you to customize every part of it to suit your business needs. This guide presents customization options **in order of recommendation** - start from the top and only move down if simpler options don't meet your needs.+Spree is designed to be customized without forking it. This guide presents the options **in order of recommendation** — start at the top and only move down when a simpler option doesn't fit.-## Quick Reference+<Note>+Business logic is extended through **workflow hooks** rather than by replacing classes wholesale, and the admin is a React application with its own extension points rather than a Rails engine extended through partials.+</Note>++## Quick reference| What you want to do | Recommended approach |-|---------------------|---------------------|-| Change store settings (currency, zones, languages) | [Store Settings](#store-settings) |+|---|---|+| Change store settings (currency, markets, languages) | [Store settings](#store-settings) || Tweak Spree behavior globally | [Configuration](#configuration) |-| React to model changes (sync, notifications) | [Events & Subscribers](#events-and-subscribers) |+| Run your own logic inside checkout, cancellation, refunds | [Workflow hooks](#workflow-hooks) |+| Block an operation from happening | [Workflow hooks](#workflow-hooks) — `validate` |+| React after something happened (sync, notifications) | [Events & subscribers](#events-and-subscribers) |+| Add or reorder checkout steps | [Checkout registry](#checkout-steps) |+| Swap tax, delivery rate, search or fulfillment behavior | [Providers](#providers) |+| Add searchable/filterable fields | [Search & filtering](#search-and-filtering) |+| Use your own user model or identity provider | [Authentication](#authentication) || Notify external services | [Webhooks](#webhooks) |-| Swap core services (cart, checkout, etc.) | [Dependencies](#dependencies) |-| Add admin menu items | [Admin Navigation](#admin-extensions) |-| Add sections to admin forms | [Admin Partials](#admin-extensions) |-| Add searchable/filterable fields | [Ransack Configuration](#search-and-filtering) |+| Replace a whole workflow or service | [Dependencies](#dependencies) || Add associations/validations to models | [Decorators](#decorators) (last resort) |+<Info>+**Customizing the admin?** This page covers the backend — models, API and business logic. The Spree 6 admin is a separate React application with its own extension points. See [Dashboard Customization](/developer/dashboard/customization/quickstart).+</Info>+<AccordionGroup><Accordion title="Store settings" defaultOpen>- **Best for:** Changing currency, shipping zones, languages, and other business settings.-- There's a lot of Store settings you can change in the admin panel without touching the code.+ **Best for:** currency, markets, delivery zones, languages, and other business settings.- Go to **Admin > Settings**-- <img src="/images/spree_admin_store_settings.png" alt="Spree Admin Store Settings" />+ Most day-to-day configuration is data, not code. Change it in the dashboard under **Settings** — no deploy required.</Accordion>-<Accordion title="Configuration">- **Best for:** Tweaking Spree's behavior globally without modifying source code.-- Global application configuration allows you to customize various aspects of Spree:+ **Best for:** tweaking Spree's behavior globally.```ruby config/initializers/spree.rbSpree.config do |config|- config.allow_guest_checkout = false- config.products_per_page = 20+ config.minimum_password_length = 10end```- Please see [Configuration](/developer/customization/configuration) section for more information.+ See [Configuration](/developer/customization/configuration).</Accordion>-- <Accordion title="Events and Subscribers">- **Best for:** Reacting to model changes, syncing with external services, sending notifications, audit logging.+ <Accordion title="Workflow hooks">+ **Best for:** running your own logic *inside* a core flow — checkout completion, order cancellation, refunds, fulfillment creation.<Info>- Events are the **recommended way** to add behavior when something happens in Spree, replacing the need for decorator callbacks.+ Hooks are the **headline extension point in Spree 6**. Before them, customizing a flow meant replacing the entire class and keeping your copy in sync with core forever.</Info>- Spree's event system lets you subscribe to events like `order.completed`, `product.updated`, `payment.paid`, etc.:-- ```ruby app/subscribers/order_completed_subscriber.rb- class OrderCompletedSubscriber < Spree::Subscriber- subscribes_to 'order.completed'-- def handle(event)- order = Spree::Order.find_by_prefix_id(event.payload['id'])- return unless order+ Register a handler against a hook key — `<workflow key>.<hook name>`:- # Sync to external service, send notification, etc.- ExternalService.notify_order_placed(order)- end+ ```ruby config/initializers/spree.rb+ Spree.hooks.register('carts.complete.validate') do |flow|+ flow.reject!('We cannot deliver to this region') unless deliverable?(flow.cart)end```- **Key benefits:**- - Loose coupling - your code doesn't depend on Spree internals- - Async by default - keeps requests fast- - Easier testing and upgrades-- Please see [Events](/developer/core-concepts/events) section for more information.- </Accordion>+ Pass a class instead of a block for anything longer than a line:- <Accordion title="Webhooks">- **Best for:** Notifying external services (ERPs, CRMs, fulfillment systems) when events occur.+ ```ruby+ Spree.hooks.register('carts.complete.after_finalize', 'MyApp::PushOrderToERP')+ ```- Webhooks send HTTP POST requests to external URLs when Spree events happen:+ There are three families of hook:- - Order completed → Notify fulfillment system- - Product updated → Sync with PIM- - Customer created → Add to CRM+ | Family | Naming | What it can do |+ |---|---|---|+ | **validate** | `validate` | Veto the operation with `flow.reject!(message)` |+ | **lifecycle** | past tense — `after_finalize`, `after_cancel` | React to what happened; read-only |+ | **context** | `set_*_context`, `get_provider_data` | Return a hash that gets merged into the flow's data |- Configure webhooks in **Admin > Developers > Webhooks** or via the API.+ Hook keys are validated after boot, so a typo fails startup rather than silently never running.- Please see [Webhooks](/developer/core-concepts/webhooks) section for more information.+ See [Services & Workflows](/developer/customization/workflows) for the full list of flows and their hooks.</Accordion>+ <Accordion title="Events and subscribers">+ **Best for:** reacting *after* something happened — syncing to external systems, notifications, audit logging.- <Accordion title="Dependencies">- **Best for:** Swapping core services, serializers, and abilities with your own implementations.+ ```ruby app/subscribers/spree/order_placed_subscriber.rb+ module Spree+ class OrderPlacedSubscriber < Spree::Subscriber+ subscribes_to 'order.placed'- Spree allows you to replace core classes without modifying them:+ def handle(event)+ order = Spree::Order.find_by_prefix_id(event.payload['id'])+ return unless order- ```ruby config/initializers/spree.rb- Spree::Dependencies.cart_add_item_service = "MyCartAddItemService"- Spree::Dependencies.cart_remove_item_service = "MyCartRemoveItemService"+ MyApp::ERP.push(order)+ end+ end+ end```- This is cleaner than decorating services because you provide a complete replacement rather than patching behavior.+ **Events or hooks?** A hook runs *inside* the flow and can influence or block it. An event fires *after* the fact and cannot. Reach for an event unless you need to change the outcome.- Please see [Dependencies](dependencies) section for more information.+ See [Events](/developer/core-concepts/events).</Accordion>+ <Accordion title="Checkout steps">+ **Best for:** adding, removing or reordering checkout steps.- <Accordion title="Admin Extensions">- **Best for:** Adding menu items, form sections, dashboard widgets, and other UI elements to the admin panel.+ Spree 6 has no checkout state machine. A cart reports what it still needs, and you can add to that list:- Spree provides declarative APIs for extending the admin without decorators or view overrides:-- **Navigation API** - Add menu items:```ruby config/initializers/spree.rb- Rails.application.config.after_initialize do- Spree.admin.navigation.sidebar.add :brands,- label: :brands,- url: :admin_brands_path,- icon: 'award',- position: 35- end+ Spree::Checkout::Registry.register_step(+ name: :loyalty,+ before: :payment,+ satisfied: ->(cart) { cart.metadata['loyalty_number'].present? },+ requirements: ->(cart) {+ [{ step: 'loyalty', field: 'loyalty_number', message: 'Loyalty number is required' }]+ }+ )```- **Partials API** - Add sections to forms:- ```ruby config/initializers/spree.rb- Spree.admin.partials.product_form << 'spree/admin/products/erp_section'+ Or attach a requirement to an existing step:++ ```ruby+ Spree::Checkout::Registry.add_requirement(+ step: :payment,+ field: :po_number,+ message: 'PO number is required',+ satisfied: ->(cart) { cart.metadata['po_number'].present? }+ )```- Please see:- - [Admin Navigation](/developer/admin/navigation) - For adding menu items- - [Admin Partials](/developer/admin/extending-ui) - For extending UI- - [Admin Tables](/developer/admin/tables) - For customizing list views+ Registered requirements appear in the Cart API's `requirements` array, so your storefront renders them without duplicating any rules.++ See [Carts](/developer/core-concepts/carts#checkout-requirements).</Accordion>+ <Accordion title="Providers">+ **Best for:** swapping a whole area of behavior for your own implementation.++ Spree 6 exposes pluggable providers for the domains that vary most between businesses:- <Accordion title="Search and Filtering">- **Best for:** Making custom fields searchable/sortable in the admin and API.+ | Provider | Controls |+ |---|---|+ | Tax provider | How tax is calculated, per market |+ | Delivery rate provider | How delivery is priced — flat rates or live carrier rates |+ | Fulfillment provider | How a delivery type behaves — shipping, digital, pickup |+ | Search provider | Database or Meilisearch |+ | Payout provider | Where marketplace payouts go |- Instead of decorating models to add `ransackable_attributes`, use the Ransack configuration API:+ Each is a class you register and select on the relevant record, so no conditional code lands in core.++ See [Fulfillments](/developer/core-concepts/fulfillments#delivery-types) and [Taxes](/developer/core-concepts/taxes).+ </Accordion>+ <Accordion title="Search and filtering">+ **Best for:** making custom fields searchable and sortable in the dashboard and API.```ruby config/initializers/spree.rb- Spree.ransack.add_attribute :product, :erp_id- Spree.ransack.add_association :product, :brand+ Spree.ransack.add_attribute(Spree::Product, :erp_id)+ Spree.ransack.add_association(Spree::Product, :brand)+ Spree.ransack.add_scope(Spree::Product, :featured)```- Please see [Search & Filtering](/developer/core-concepts/search-filtering#extending-ransackable-configuration) section for more information.+ See [Search & Filtering](/developer/core-concepts/search-filtering).</Accordion>-<Accordion title="Authentication">- **Best for:** Using your own user model or authentication system.+ **Best for:** using your own user model or identity provider.- Spree allows you to use your own authentication system instead of the default Devise-based one.+ Spree 6 owns its authentication stack rather than depending on Devise, and separates the customer identity from the staff identity. Point Spree at your own classes with `Spree.user_class` and `Spree.admin_user_class`.- You can find more information in the [Authentication](authentication) section.+ See [Authentication](/developer/providers/sso).</Accordion>+ <Accordion title="Webhooks">+ **Best for:** notifying external services — ERPs, CRMs, fulfillment systems — without writing Ruby.- <Accordion title="Checkout flow">- **Best for:** Customizing checkout steps and flow.-- With Spree you can change the checkout flow to fit your business needs - add steps, remove steps, or change the order.+ Configure them in the dashboard under **Settings → Webhooks**, or through the Admin API.- Please see [Checkout flow customization section](checkout) for more information.+ See [Webhooks](/developer/core-concepts/webhooks).</Accordion>+ <Accordion title="Dependencies">+ **Best for:** replacing an entire workflow or service with your own class.- <Accordion title="Decorators">- **Best for:** Adding associations, validations, scopes, and methods to Spree models. Use as a last resort.+ ```ruby config/initializers/spree.rb+ Spree::Dependencies.cart_add_item_workflow = 'MyApp::Carts::AddItem'+ ```<Warning>- Decorators should be used **only when no other option works**. They tightly couple your code to Spree internals and can break during upgrades.+ Seam names end in `_workflow` in Spree 6. The old `*_service` names still resolve for one release with a warning, but **writes to them are ignored** — a class written against the old service contract isn't interchangeable with a workflow. Update the key when you upgrade.+ </Warning>++ Prefer a hook when you only need to add behavior. Replace the class only when you need to change what the flow fundamentally does.++ See [Dependencies](/developer/customization/dependencies).+ </Accordion>+ <Accordion title="Decorators">+ **Best for:** adding associations, validations and scopes to Spree models. Use as a last resort.- **Do NOT use decorators for:**- - After-save callbacks → Use [Events](/developer/core-concepts/events) instead- - External service sync → Use [Webhooks](/developer/core-concepts/webhooks) instead- - Custom service logic → Use [Dependencies](dependencies) instead- - Admin UI changes → Use [Admin Extensions](#admin-extensions) instead+ <Warning>+ Decorators couple your code to Spree internals and are the most common cause of painful upgrades.++ **Do not use decorators for:**+ - Logic inside a core flow → use [workflow hooks](#workflow-hooks)+ - After-save callbacks → use [events](#events-and-subscribers)+ - External service sync → use [webhooks](#webhooks)+ - Replacing a service → use [dependencies](#dependencies)+ - Admin UI changes → use [dashboard customization](/developer/dashboard/customization/quickstart)</Warning>- Decorators are still appropriate for structural changes:+ They remain appropriate for structural additions:```ruby app/models/spree/product_decorator.rbmodule Spreemodule ProductDecoratordef self.prepended(base)base.belongs_to :brand, class_name: 'MyApp::Brand', optional: true- base.validates :external_id, presence: truebase.scope :featured, -> { where(featured: true) }end@@ -195,6 +224,28 @@ Spree is a flexible platform allowing you to customize every part of it to suitend```- Please see [Decorators](decorators) section for more information.+ See [Decorators](/developer/customization/decorators).</Accordion></AccordionGroup>++## Choosing between hooks, events and dependencies++These three overlap, and picking the wrong one is the most common source of upgrade pain:++<Steps>+ <Step title="Do you need to block or change the outcome?">+ Use a **workflow hook**. Only `validate` hooks can stop an operation, and only they run early enough to do so safely — before money moves.+ </Step>+ <Step title="Do you just need to know it happened?">+ Use an **event subscriber**. It's decoupled, testable, and survives upgrades untouched.+ </Step>+ <Step title="Do you need the flow to do something fundamentally different?">+ Use **dependencies** to replace the class — and accept that you now own keeping it current.+ </Step>+</Steps>++## Related++- [Services & Workflows](/developer/customization/workflows) — the workflow model and every hook+- [Carts](/developer/core-concepts/carts) — checkout requirements and completion+- [Dashboard Customization](/developer/dashboard/customization/quickstart) — extending the admindiff --git a/docs/developer/customization/validations.mdx b/docs/developer/customization/validations.mdxindex eaea86cee7..f90449e0f9 100644--- a/docs/developer/customization/validations.mdx+++ b/docs/developer/customization/validations.mdx@@ -162,7 +162,7 @@ Spree::Checkout::Registry.add_requirement()```-See the [Spree 6 quickstart](/v6/developer/customization/quickstart) for the full registry API.+See the [Spree 6 quickstart](/developer/customization/quickstart) for the full registry API.## Custom field valuesdiff --git a/docs/developer/dashboard/overview.mdx b/docs/developer/dashboard/overview.mdxindex 8a0fd40625..29eeef5858 100644--- a/docs/developer/dashboard/overview.mdx+++ b/docs/developer/dashboard/overview.mdx@@ -104,4 +104,4 @@ When in doubt, customize in-app first. The migration path to a plugin is mechani- [Plugin scaffolding](/developer/dashboard/plugins/scaffolding)- [Slots catalog](/developer/dashboard/slots-catalog) — every named slot the dashboard exposes- [`@spree/dashboard-core` README](https://github.com/spree/spree/tree/main/packages/dashboard-core) — full extension API reference-- [Classic Admin extension model](/developer/admin/extending-ui) — for Spree 5.x+- [Classic Admin extension model](/developer/dashboard/customization/quickstart) — for Spree 5.xdiff --git a/docs/developer/how-to/build-a-b2b-store.mdx b/docs/developer/how-to/build-a-b2b-store.mdxnew file mode 100644index 0000000000..c508d4c247--- /dev/null+++ b/docs/developer/how-to/build-a-b2b-store.mdx@@ -0,0 +1,21 @@+---+title: Build a B2B Store+description: Wholesale pricing, customer groups, companies with tax exemption, and gated storefront access — assembling Spree's B2B capabilities into a working wholesale channel.+---++Spree's B2B capabilities are core features composed together rather than a separate product: price lists give buyers negotiated and volume pricing, customer groups segment who sees what, companies carry the legal and tax identity of the buyer, and channel access controls gate the storefront to signed-in buyers.++## What you will build++- **Wholesale pricing** — price lists scoped to customer groups, volume tiers, and regional pricing per market.+- **Companies** — buyer organizations with locations and contacts, tax identifiers validated per jurisdiction, and tax exemption certificates applied at checkout.+- **Gated access** — a storefront channel restricted to approved buyers, with guest checkout disabled.+- **B2B checkout** — orders carrying the buying company and location, priced and taxed accordingly.++## Outline++1. Model your buyer segments as customer groups+2. Build wholesale price lists and volume tiers+3. Register companies, locations and tax exemptions+4. Gate a sales channel for wholesale buyers+5. Take a wholesale order end to enddiff --git a/docs/developer/how-to/build-a-marketplace.mdx b/docs/developer/how-to/build-a-marketplace.mdxnew file mode 100644index 0000000000..07548a52c7--- /dev/null+++ b/docs/developer/how-to/build-a-marketplace.mdx@@ -0,0 +1,27 @@+---+title: Build a Multi-Vendor Marketplace+description: Marketplace capabilities are part of Spree 6 core — sellers, order splitting, commissions and payouts, without a separate extension.+---++<Note>+Marketplace features are a headline capability of the Spree 6.0 release and are documented here as they land. This guide covers the open-source core.+</Note>++Spree 6 brings multi-vendor marketplace support into the open-source core: sellers as first-class records, orders split per seller at completion, a commission engine, and a payout ledger with pluggable payout providers.++## What you will build++- **Sellers** — onboard sellers with an operator-configured requirements checklist, review submissions, and approve them for selling.+- **Order splitting** — a customer checks out once; completion produces per-seller orders grouped under one purchase.+- **Commissions** — the platform's cut computed per seller, with EU commission taxation handled.+- **Payouts** — a transfer and payout ledger, with Stripe Connect payouts (Express onboarding, on-fulfillment transfers) shipping in the open-source monorepo.+- **Seller operations** — sellers work through their own dedicated API surface, scoped so a seller only ever sees their own trade.++## Outline++1. Enable marketplace capabilities and configure the store+2. Define seller onboarding requirements+3. Invite and approve sellers+4. Assign catalog to sellers and take a multi-seller order through checkout+5. Configure commissions+6. Connect Stripe for payoutsdiff --git a/docs/developer/how-to/custom-api-authentication.mdx b/docs/developer/how-to/custom-api-authentication.mdxindex 3f7c188bf4..ed82898c79 100644--- a/docs/developer/how-to/custom-api-authentication.mdx+++ b/docs/developer/how-to/custom-api-authentication.mdx@@ -395,4 +395,4 @@ end- `Spree::Api::V3::Store::AuthController` — `spree/api/app/controllers/spree/api/v3/store/auth_controller.rb`- `Spree::Api::V3::Admin::AuthController` — `spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb`- `Spree::Api::V3::JwtAuthentication` — `spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb`-- See also: [Staff & Roles](/developer/core-concepts/staff-roles) for the admin login flow, [Customers](/developer/core-concepts/customers) for storefront auth, and [Authentication](/developer/customization/authentication) for `Spree.user_class` integration.+- See also: [Staff & Roles](/developer/core-concepts/staff-roles) for the admin login flow, [Customers](/developer/core-concepts/customers) for storefront auth, and [Authentication](/developer/providers/sso) for `Spree.user_class` integration.diff --git a/docs/v6/developer/how-to/custom-delivery-rate-provider.mdx b/docs/developer/how-to/custom-delivery-rate-provider.mdxsimilarity index 98%rename from docs/v6/developer/how-to/custom-delivery-rate-provider.mdxrename to docs/developer/how-to/custom-delivery-rate-provider.mdxindex d1d4f27c51..68054a8570 100644--- a/docs/v6/developer/how-to/custom-delivery-rate-provider.mdx+++ b/docs/developer/how-to/custom-delivery-rate-provider.mdx@@ -9,7 +9,7 @@ A delivery rate provider decides **where a delivery method's price comes from**.A custom provider replaces that arithmetic with a live quote: you call a carrier or an aggregator, and the rate that reaches checkout carries the carrier name, the service level, and an estimated delivery date.-Use a provider when the price comes from outside Spree. If you only need different arithmetic on values Spree already has, write a calculator instead — it is far less work. See [Fulfillments](/v6/developer/core-concepts/fulfillments) for how delivery methods, rates and fulfillments fit together.+Use a provider when the price comes from outside Spree. If you only need different arithmetic on values Spree already has, write a calculator instead — it is far less work. See [Fulfillments](/developer/core-concepts/fulfillments) for how delivery methods, rates and fulfillments fit together.## What you will build@@ -166,7 +166,7 @@ Providers and calculators coexist freely. A store can price "Free shipping" withOnce a parcel is moving, most carriers will tell you where it is. Spree keepsthat on a separate field from the fulfillment's own status, so a bounced parcel-never un-ships itself — see [Fulfillments](/v6/developer/core-concepts/fulfillments#statuses).+never un-ships itself — see [Fulfillments](/developer/core-concepts/fulfillments#statuses).Spree owns the endpoint: every integration gets one at`POST /api/v3/webhooks/fulfillments/:integration_id` — the merchant pastesdiff --git a/docs/v6/developer/how-to/custom-document-numbers.mdx b/docs/developer/how-to/custom-document-numbers.mdxsimilarity index 100%rename from docs/v6/developer/how-to/custom-document-numbers.mdxrename to docs/developer/how-to/custom-document-numbers.mdxdiff --git a/docs/developer/how-to/custom-order-routing.mdx b/docs/developer/how-to/custom-order-routing.mdxindex 1969308bf4..9dd54421c6 100644--- a/docs/developer/how-to/custom-order-routing.mdx+++ b/docs/developer/how-to/custom-order-routing.mdx@@ -16,7 +16,7 @@ Order routing decides which [Stock Location](/developer/core-concepts/inventory#This guide covers both. Most extensions are rules — they compose with the built-ins and don't require rewriting the pipeline.-Before starting, make sure you understand [how order routing works in Spree](/developer/core-concepts/shipments#order-routing).+Before starting, make sure you understand [how order routing works in Spree](/developer/core-concepts/fulfillments#order-routing).| If the answer is "yes" | Pick ||---|---|diff --git a/docs/developer/how-to/custom-payment-method.mdx b/docs/developer/how-to/custom-payment-method.mdxindex 1a1411cfcb..c768d76432 100644--- a/docs/developer/how-to/custom-payment-method.mdx+++ b/docs/developer/how-to/custom-payment-method.mdx@@ -370,7 +370,7 @@ For every gateway action (authorize, purchase, capture, void, credit), Spree pas## Related Documentation- [Payments](/developer/core-concepts/payments) - Payment architecture and core concepts-- [Checkout Customization](/developer/customization/checkout) - Customizing the checkout flow+- [Checkout Customization](/developer/core-concepts/carts) - Customizing the checkout flow- [Events](/developer/core-concepts/events) - Subscribe to payment events- [Stripe Integration](/integrations/payments/stripe) - Reference implementation using Stripe- [Adyen Integration](/integrations/payments/adyen) - Reference implementation using Adyendiff --git a/docs/developer/how-to/custom-promotion.mdx b/docs/developer/how-to/custom-promotion.mdxindex 81f059e2f8..62ec4fcb25 100644--- a/docs/developer/how-to/custom-promotion.mdx+++ b/docs/developer/how-to/custom-promotion.mdx@@ -1,18 +1,17 @@---title: Build Custom Promotion Rules & Actions-description: Step-by-step guide to creating custom promotion rules and actions for business-specific eligibility logic and discount behaviors.+description: Step-by-step guide to creating custom promotion rules, discount actions, and adjusters for business-specific eligibility logic and charges.---## Overview-Spree's promotion system is built around two extension points: **Rules** (eligibility conditions) and **Actions** (what happens when a promotion applies). While Spree ships with a comprehensive set of [built-in rules and actions](/developer/core-concepts/promotions#rules), you can create custom ones for business-specific logic.+Spree's promotion system has three extension points:-This guide covers:-- Creating a custom promotion rule with admin UI-- Creating a custom promotion action with a calculator-- Understanding the `eligible?`, `actionable?`, and `perform` contracts+- **Rules** — conditions that decide when a promotion applies+- **Actions** — what an applied promotion does, usually writing [Discount](/developer/core-concepts/taxes-discounts-fees#discounts) rows+- **Adjusters** — for discounts and fees that aren't promotions at all (loyalty pricing, gift wrap fees, payment surcharges)-Before starting, make sure you understand [how promotions work in Spree](/developer/core-concepts/promotions).+Spree ships with a comprehensive set of [built-in rules and actions](/developer/core-concepts/promotions#rules). This guide shows how to build your own of each kind.## Custom Promotion Rules@@ -30,7 +29,7 @@ module Spreepreference :quantity, :integer, default: 5def applicable?(promotable)- promotable.is_a?(Spree::Order)+ promotable.is_a?(Spree::Order) || promotable.is_a?(Spree::Cart)enddef eligible?(order, options = {})@@ -56,12 +55,16 @@ end| Method | Required | Description ||--------|----------|-------------|-| `applicable?(promotable)` | Yes | Returns `true` if this rule type can evaluate the promotable (usually `promotable.is_a?(Spree::Order)`) |+| `applicable?(promotable)` | Yes | Returns `true` if this rule type can evaluate the promotable — accept both carts and orders (see the note below) || `eligible?(promotable, options = {})` | Yes | Returns `true` if the promotable meets this rule's conditions. Add messages to `eligibility_errors` to explain why not. |-| `actionable?(line_item)` | No | Returns `true` if a specific line item should receive the promotion's action. Defaults to `true`. Override this for rules that target specific items (like product or category rules). |+| `actionable?(line_item)` | No | Returns `true` if a specific line item should receive the promotion's discount. Defaults to `true`. Override this for rules that target specific items (like product or category rules). |The `options` hash passed to `eligible?` can include `:user`, `:email`, and other context from the checkout flow.+<Warning>+Accept **both** `Spree::Cart` and `Spree::Order` in `applicable?`. Promotions are evaluated on every cart change, long before the cart becomes an order, and in Spree 6 a cart is its own model rather than an unfinished order. A rule guarding on `Spree::Order` alone silently never applies during checkout — the promotion just appears not to work. Every built-in rule accepts both.+</Warning>+#### Using PreferencesRules use Spree's preference system for configuration. Each preference creates getter/setter methods automatically:@@ -81,43 +84,30 @@ Available types: `:string`, `:integer`, `:decimal`, `:boolean`, `:array`.### Step 2: Register the Rule-Add your rule to the promotion configuration so it appears in the admin panel:-```ruby config/initializers/spree.rbRails.application.config.after_initialize doSpree.promotions.rules << Spree::Promotion::Rules::MinimumQuantityend```-### Step 3: Create the Admin Partial--Create a form partial so admins can configure the rule's preferences. The partial name must match the rule class name in underscore format:+Registered rules are discoverable at `/api/v3/admin/promotion_rules/types` together with their preference schema, and the dashboard's promotion editor is built on that endpoint — your rule appears there with a generated preferences form, no UI work needed.-```erb app/views/spree/admin/promotions/rules/_minimum_quantity.html.erb-<div class="row mb-3">- <%= f.spree_number_field :preferred_quantity, label: Spree.t(:minimum_quantity) %>-</div>-```+### Step 3: Add Translations-### Step 4: Add Translations+The rule's display name and description in the dashboard come from your locale file:```yaml config/locales/en.ymlen:spree:- minimum_quantity: Minimum Quantitypromotion_rule_types:minimum_quantity:name: Minimum Quantitydescription: Order must contain at least X items```-### Step 5: Restart and Test--After restarting your application, the new rule will be available in **Admin > Promotions** when adding rules to a promotion.-### Example: Rule with `actionable?`-When your rule targets specific line items (not the whole order), implement `actionable?` so that actions like `CreateItemAdjustments` only discount matching items:+When your rule targets specific line items (not the whole order), implement `actionable?` so that item-level actions only discount matching items:```ruby app/models/spree/promotion/rules/brand.rbmodule Spree@@ -127,7 +117,7 @@ module Spreepreference :brand_names, :array, default: []def applicable?(promotable)- promotable.is_a?(Spree::Order)+ promotable.is_a?(Spree::Order) || promotable.is_a?(Spree::Cart)enddef eligible?(order, options = {})@@ -153,13 +143,17 @@ end## Custom Promotion Actions-Actions define what happens when a promotion is applied. Most actions create [adjustments](/developer/core-concepts/adjustments) on orders or line items.+Actions define what happens when a promotion is applied. A discount action doesn't write rows itself — it declares **where** its discount belongs and **how much** it is, and Spree's promotion engine does the rest: running the competition between promotions, clamping amounts so nothing goes below zero, writing the winning Discount rows, and removing stale ones on every recalculation.-### Step 1: Create the Action Class+### Discount Action (with Calculator)-#### Discount Action (with Calculator)+Three declarations make a discount action:-For actions that create monetary adjustments, include `Spree::CalculatedAdjustments` and `Spree::AdjustmentSource`:+| Method | Description |+|--------|-------------|+| `discount_scope` | Where the discount belongs: `:line_item` (per matching item), `:fulfillment` (per delivery), or `:order` (whole order, distributed proportionally across items) |+| `compute_amount(adjustable)` | The discount for one adjustable — a line item, fulfillment, or the order, matching your scope. Return a **negative** amount, or zero for "no discount". |+| `perform(options = {})` | Called when the promotion is activated. For discount actions, delegate to `apply_via_adjuster(options)`. |```ruby app/models/spree/promotion/actions/tiered_discount.rbmodule Spree@@ -167,15 +161,15 @@ module Spreemodule Actionsclass TieredDiscount < Spree::PromotionActioninclude Spree::CalculatedAdjustments- include Spree::AdjustmentSourcebefore_validation -> { self.calculator ||= Calculator::FlatRate.new }- def perform(options = {})- order = options[:order]- return false unless order.present?+ def discount_scope+ :order+ end- create_unique_adjustment(order, order)+ def perform(options = {})+ apply_via_adjuster(options)enddef compute_amount(order)@@ -186,8 +180,7 @@ module Spreeelse 0end- # Must return negative amount for discounts- # Cap at order total to prevent negative orders+ # Negative for discounts, capped at the order total[discount, order.item_total].min * -1endend@@ -196,9 +189,15 @@ module Spreeend```-#### Non-Discount Action+With `discount_scope :order`, the winning amount is shared out proportionally across the line items — you never handle the distribution yourself. With `:line_item`, `compute_amount` is called once per line item, and only items passing your rules' `actionable?` receive rows.++<Note>+There is nothing to clean up either. If the promotion stops being eligible — the cart shrinks below the threshold, the code is removed — the next recalculation deletes its rows. If your action loses to a better promotion, its candidate simply isn't written that round, and it competes again on the next one.+</Note>-For actions that don't create adjustments (e.g., awarding points, sending notifications):+### Non-Discount Action++For actions that don't create discounts (awarding points, sending notifications), implement `perform` alone:```ruby app/models/spree/promotion/actions/add_loyalty_points.rbmodule Spree@@ -220,45 +219,9 @@ module Spreeend```-#### Key Methods to Implement--| Method | Required | Description |-|--------|----------|-------------|-| `perform(options = {})` | Yes | Called when the promotion is activated. `options` includes `:order` and `:promotion`. Return `true` if the action was applied. |-| `compute_amount(adjustable)` | For discount actions | Return the adjustment amount (negative for discounts). Cap at the adjustable's total to prevent negative amounts. |-| `revert(options = {})` | No | Called when a promotion is deactivated. Use to undo side effects (e.g., remove added line items). |--#### Available Helper Methods--When you include `Spree::AdjustmentSource`, you get:--```ruby-# Create a single adjustment (e.g., on the order)-create_unique_adjustment(order, adjustable)--# Create adjustments on multiple items (e.g., all line items)-create_unique_adjustments(order, order.line_items)--# With a filter block (e.g., only actionable line items)-create_unique_adjustments(order, order.line_items) do |line_item|- promotion.line_item_actionable?(order, line_item)-end-```--When you include `Spree::CalculatedAdjustments`, you get:--```ruby-# Delegate to the calculator-compute(adjustable) # calls calculator.compute(adjustable)--# Set calculator by class name-self.calculator_type = 'Spree::Calculator::FlatRate'--# List available calculators for this action type-self.class.calculators-```+`perform` receives `:order` and `:promotion` in its options and should return `true` if the action was applied. Optionally implement `revert(options = {})` to undo side effects when the promotion is deactivated.-### Step 2: Register the Action+### Register and Translate```ruby config/initializers/spree.rbRails.application.config.after_initialize do@@ -266,8 +229,6 @@ Rails.application.config.after_initialize doend```-### Step 3: Add Translations-```yaml config/locales/en.ymlen:spree:@@ -277,39 +238,43 @@ en:description: Different discount amounts based on order total tiers```-### Step 4: Restart and Test--After restarting, the new action will be available in **Admin > Promotions** when adding actions to a promotion.--## How Rules and Actions Work Together--Understanding how Spree evaluates promotions helps you build better custom rules and actions:--```mermaid-flowchart TD- A[Order Updated] --> B[PromotionHandler::Cart]- B --> C{For each promotion}- C --> D{Check dates & usage}- D -->|expired/exceeded| E[Deactivate]- D -->|valid| F{Evaluate rules}- F -->|match_policy: all| G[ALL rules must pass]- F -->|match_policy: any| H[ANY rule must pass]- G -->|eligible| I[Run actions]- H -->|eligible| I- G -->|ineligible| E- H -->|ineligible| E- I --> J[action.perform for each action]- J --> K[Create adjustments]- K --> L[Best promotion wins]+Like rules, registered actions surface automatically in the dashboard's promotion editor via `/api/v3/admin/promotion_actions/types`.++## Custom Adjusters++Not every charge or reduction is a promotion. A gift wrap fee, a payment surcharge, or loyalty pricing has no rules, no coupon codes, and no competition — it just needs to be on the order whenever it applies. That's an **adjuster**: a class invoked on every recalculation that owns a family of [Fee or Discount](/developer/core-concepts/taxes-discounts-fees) rows.++```ruby app/models/my_app/adjusters/gift_wrap.rb+module MyApp+ module Adjusters+ class GiftWrap < Spree::Adjusters::Base+ def update+ if order.gift_wrap?+ order.fees.find_or_initialize_by(kind: 'gift_wrap').update!(+ amount: 5.99, label: 'Gift wrapping'+ )+ else+ order.fees.where(kind: 'gift_wrap').destroy_all+ end+ end+ end+ end+end+```++```ruby config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.adjusters << MyApp::Adjusters::GiftWrap+end```-**Key points:**-- `match_policy: 'all'` means every rule must return `eligible? == true`-- `match_policy: 'any'` means at least one rule must return `eligible? == true`-- For item-level actions (`CreateItemAdjustments`), `actionable?(line_item)` on each rule filters which line items get the discount-- When multiple promotions compete, Spree picks the best one (largest discount) and marks others as ineligible+The contract is one method: `update`. It runs on every recalculation, so it must be idempotent — write the rows that should exist, remove the ones that shouldn't (that's why the example uses `find_or_initialize_by` keyed by `kind` rather than `create`). The `order` it receives is the cart during checkout and the order after placement, and rows attach to it either way.++There's no totals bookkeeping to do: after all adjusters run, Spree re-sums the typed rows into the order totals and the tax provider estimates tax on the result — a fee you write here gets taxed in the same pass, like any other fee.++Custom discounts work the same way, writing `order.discounts` rows with your own `kind` (e.g. `'loyalty'`). Use a kind other than `'promotion'` — promotion rows belong to the promotion engine, which removes any it didn't write itself.-## Testing Custom Rules and Actions+## Testing```ruby spec/models/spree/promotion/rules/minimum_quantity_spec.rbrequire 'spec_helper'@@ -367,7 +332,7 @@ end## Related Documentation-- [Promotions](/developer/core-concepts/promotions) - Promotion architecture and built-in rules/actions-- [Calculators](/developer/core-concepts/calculators) - Available calculator types for promotion actions-- [Adjustments](/developer/core-concepts/adjustments) - How adjustments work on orders and line items-- [Events](/developer/core-concepts/events) - Subscribe to promotion events+- [Promotions](/developer/core-concepts/promotions) — promotion architecture and built-in rules and actions+- [Taxes, Discounts & Fees](/developer/core-concepts/taxes-discounts-fees) — the typed rows actions and adjusters write+- [Calculators](/developer/core-concepts/calculators) — available calculator types for promotion actions+- [Events](/developer/core-concepts/events) — subscribe to promotion eventsdiff --git a/docs/developer/how-to/custom-report.mdx b/docs/developer/how-to/custom-report.mdxindex 2c31270d43..0045e460cb 100644--- a/docs/developer/how-to/custom-report.mdx+++ b/docs/developer/how-to/custom-report.mdx@@ -9,7 +9,7 @@ Spree's reporting system is designed for extension. Each report is a pair of claThis guide walks you through building a custom report from scratch, including advanced patterns for SQL aggregations and multi-vendor support.-Before starting, make sure you understand [how the reporting system works](/developer/core-concepts/reports).+Before starting, make sure you understand [how the reporting system works](/v5/developer/core-concepts/reports).## Creating a Custom Report@@ -383,5 +383,5 @@ end## Related Documentation-- [Reports](/developer/core-concepts/reports) - Report architecture and built-in reports+- [Reports](/v5/developer/core-concepts/reports) - Report architecture and built-in reports- [Events](/developer/core-concepts/events) - How report generation uses the events systemdiff --git a/docs/developer/how-to/custom-stock-splitter.mdx b/docs/developer/how-to/custom-stock-splitter.mdxindex 0052251c0c..cc4d06366f 100644--- a/docs/developer/how-to/custom-stock-splitter.mdx+++ b/docs/developer/how-to/custom-stock-splitter.mdx@@ -5,11 +5,11 @@ description: Step-by-step guide to extending Spree's stock splitter chain — br## Overview-When [Order Routing](/developer/core-concepts/shipments#order-routing) picks one or more stock locations to fulfill an order, each location's allocation is then run through a chain of **splitters**. Each splitter looks at the packages produced so far and decides whether to break them further along its own axis.+When [Order Routing](/developer/core-concepts/fulfillments#order-routing) picks one or more stock locations to fulfill an order, each location's allocation is then run through a chain of **splitters**. Each splitter looks at the packages produced so far and decides whether to break them further along its own axis.Spree ships with four splitters out of the box (`ShippingCategory`, `Backordered`, `Digital`, `Weight`). You add your own when you need a *physical* separation that isn't expressed by any of the existing ones — refrigerated SKUs that can't share a box with ambient ones, hazmat goods that need their own carrier label, gift-wrap items that ship from a separate processing room, and so on.-Before starting, make sure you understand [how splitting works in Spree](/developer/core-concepts/shipments#stock-splitters) and the [order routing](/developer/core-concepts/shipments#order-routing) layer that runs before splitters.+Before starting, make sure you understand [how splitting works in Spree](/developer/core-concepts/fulfillments#stock-splitters) and the [order routing](/developer/core-concepts/fulfillments#order-routing) layer that runs before splitters.| If the answer is "yes" | Pick ||---|---|@@ -170,7 +170,7 @@ end### Step 4 (optional): Add a Variant-side Predicate-The example above relies on `variant.refrigerated?`. In a real plugin you'd back that with a [Custom Field](/developer/core-concepts/custom-fields) on `Spree::Variant` — say a boolean metafield with key `refrigerated` — and define the predicate as a thin reader:+The example above relies on `variant.refrigerated?`. In a real plugin you'd back that with a [Custom Field](/developer/core-concepts/metafields) on `Spree::Variant` — say a boolean metafield with key `refrigerated` — and define the predicate as a thin reader:```ruby app/models/spree/variant_decorator.rbSpree::Variant.class_eval do@@ -208,6 +208,6 @@ Practical implications:## Next Steps-- [Shipments — Stock Splitters](/developer/core-concepts/shipments#stock-splitters) — Concept overview and built-in splitter list+- [Shipments — Stock Splitters](/developer/core-concepts/fulfillments#stock-splitters) — Concept overview and built-in splitter list- [Build Custom Order Routing](/developer/how-to/custom-order-routing) — The other layer of split-shipment customization-- [Custom Fields](/developer/core-concepts/custom-fields) — Tag variants with the data your splitter reads+- [Custom Fields](/developer/core-concepts/metafields) — Tag variants with the data your splitter readsdiff --git a/docs/developer/how-to/sell-digital-products.mdx b/docs/developer/how-to/sell-digital-products.mdxnew file mode 100644index 0000000000..c8fc60e634--- /dev/null+++ b/docs/developer/how-to/sell-digital-products.mdx@@ -0,0 +1,20 @@+---+title: Sell Digital Products+description: Digital goods in Spree — a digital delivery profile, instant fulfillment without a shipping address, and delivering files or entitlements after payment.+---++Digital products skip the warehouse: no stock to reserve, no address to collect, no carrier to call. In Spree 6 that behavior comes from the product's delivery profile — assign a digital profile and checkout, fulfillment and the customer experience adapt.++## What you will build++- **Digital delivery profile** — products that require no shipping address and complete checkout without a delivery step.+- **Instant fulfillment** — the digital fulfillment provider fulfills on payment rather than on dispatch.+- **Delivery of the goods** — attaching files or granting entitlements, and notifying the customer.+- **Mixed carts** — physical and digital items in one order, split into separate fulfillments automatically.++## Outline++1. Create a digital delivery profile and assign products+2. Configure the digital fulfillment provider+3. Deliver files or entitlements on fulfillment+4. Handle mixed physical and digital ordersdiff --git a/docs/developer/multi-tenant/quickstart.mdx b/docs/developer/multi-tenant/quickstart.mdxindex ca35a8d86c..f3662ba041 100644--- a/docs/developer/multi-tenant/quickstart.mdx+++ b/docs/developer/multi-tenant/quickstart.mdx@@ -23,7 +23,7 @@ Each tenant (store) can have its own isolated data and configuration, including:All data is fully isolated besides the staff users, which can manage multiple tenants. This allows you to create a SaaS platform where each tenant can have its own store with its own branding and configuration. Isolation works across admin dashboard and API.<Info>- If you need individual seller/supplier/vendor accounts but shared product listings under one site you should use [multi vendor recipe](/developer/multi-vendor) instead.+ If you need individual seller/supplier/vendor accounts but shared product listings under one site you should use [multi vendor recipe](/developer/how-to/build-a-marketplace) instead.</Info>## Prerequisitesdiff --git a/docs/developer/providers/dam.mdx b/docs/developer/providers/dam.mdxnew file mode 100644index 0000000000..7d6c26c077--- /dev/null+++ b/docs/developer/providers/dam.mdx@@ -0,0 +1,16 @@+---+title: Product Media & DAM+description: Media hosted in your DAM stays in your DAM — Spree stores the address, not a copy of the bytes, and renders it through the same pipeline as uploaded media.+---++<Note>+This page documents functionality landing in an upcoming Spree 6.0 release. The interfaces described here may change before final release.+</Note>++If your media lives in a digital asset management system or a CDN you already operate, importing copies into Spree doubles your storage and guarantees drift. Externally hosted media makes the address the record: Spree stores a URL, renders it wherever uploaded media renders, and your DAM remains the source of truth for the asset itself.++## What this covers++- Product images and videos referenced by URL instead of uploaded bytes+- Feeding media URLs through the same product feeds and imports as the rest of your catalog data+- How externally hosted media behaves in the dashboard, the APIs and the storefront alongside uploaded mediadiff --git a/docs/developer/providers/erp.mdx b/docs/developer/providers/erp.mdxnew file mode 100644index 0000000000..525a1327d7--- /dev/null+++ b/docs/developer/providers/erp.mdx@@ -0,0 +1,33 @@+---+title: Connect Your ERP+description: Keep your ERP as the source of truth for stock. Spree syncs inventory in, answers availability from its own snapshot, and asks your ERP live only at the moments that matter.+---++<Note>+This page documents functionality landing in an upcoming Spree 6.0 release. The interfaces described here may change before final release.+</Note>++Your ERP owns inventory truth. Spree's job is to sell against it without keeping a copy that drifts — and without making every product page wait on an ERP round trip.++## What syncs, what stays live++Stock levels sync into Spree and availability renders from Spree's own records. Live calls to the inventory provider happen only at decision moments: add-to-cart, taking a hold, completing checkout. Anonymous browsing never waits on your ERP.++## The inventory provider++A provider answers stock questions with Spree's own stock record shape, so everything downstream — backorder limits, serializers, availability scopes — keeps working without knowing where the number came from. External answers are read-only and never written into the catalog. The default provider reads Spree's own stock records; connecting nothing changes nothing.++## Feeding stock from your ERP++Two ways in, both writing stock movements rather than overwriting numbers — so you can always see why a figure changed:++- **Bulk stock endpoint** — batch updates addressed by Spree IDs or by the keys your ERP already uses.+- **CSV stock import** — file-based feeds through the standard import pipeline.++## Addressing records by your keys++The same product is known to your ERP and your PIM under different keys. External references are store-scoped mappings that let any feed address a Spree record as `external:<system>:<id>` — a create that names a key Spree already knows updates that record instead of failing.++## Checkout holds and failure policy++Local checkout holds reduce availability against externally reported stock, matched by location, so reservations count correctly. When your ERP is unreachable, inventory falls back to the local snapshot — selling stock that turns out to be missing is recoverable; blocking every checkout is not.diff --git a/docs/developer/providers/fulfillment.mdx b/docs/developer/providers/fulfillment.mdxnew file mode 100644index 0000000000..0fd440aae9--- /dev/null+++ b/docs/developer/providers/fulfillment.mdx@@ -0,0 +1,25 @@+---+title: Shipping & WMS+description: Connect your warehouse, 3PL or carrier stack through fulfillment providers — label purchase, tracking, and delivery confirmation flow through one contract.+---++When an order ships, something outside Spree does the physical work — a warehouse management system, a 3PL, or a carrier API. Fulfillment providers are the contract between Spree's fulfillment lifecycle and that system.++## What a fulfillment provider does++A provider is attached to a delivery method and owns the outbound side of shipping:++- **Label purchase** — providers that generate labels declare it and buy the label *before* the fulfillment is marked as shipped, so the customer email always carries tracking. Labels can also be purchased explicitly ahead of dispatch.+- **Carrier notification** — creating a fulfillment with the provider is idempotent; cancelling or resuming a fulfillment stands the carrier down or re-engages it.++## Tracking is its own axis++Carrier truth — in transit, out for delivery, delivered — is tracked separately from Spree's fulfillment status. Tracking updates flow in from carrier webhooks and update the tracking status without touching the fulfillment lifecycle; confirmed delivery anchors the returns window.++## The EasyPost reference provider++The `spree_easypost` gem ships in the monorepo as the reference implementation: live carrier rates, label purchase and refunds, and tracker webhooks, with credentials managed through a Spree integration.++## Writing your own++A WMS or 3PL integration implements the same contract: receive the fulfillment, do the physical work, report tracking back. Rate quoting is a separate, smaller contract — see [custom delivery rates](/developer/how-to/custom-delivery-rate-provider).diff --git a/docs/developer/providers/observability.mdx b/docs/developer/providers/observability.mdxnew file mode 100644index 0000000000..eafbae9857--- /dev/null+++ b/docs/developer/providers/observability.mdx@@ -0,0 +1,218 @@+---+title: Observability+description: Distributed tracing with OpenTelemetry — one gem, standard OTEL_* environment variables, and every checkout becomes a trace from HTTP request to gateway call to webhook delivery.+---++Spree supports [OpenTelemetry](https://opentelemetry.io), the open standard for+distributed tracing. Install the optional `spree_opentelemetry` gem, point it+at your collector with the same environment variables every other+OpenTelemetry service uses, and Spree exports traces — no code changes, no+vendor lock-in. Traces flow to any OpenTelemetry-compatible backend: Grafana+Tempo, Jaeger, Datadog, Honeycomb, New Relic, Dynatrace, and others.++## Setup++Add the gem to your application's Gemfile:++```ruby+gem 'spree_opentelemetry'+```++Then configure the exporter through the standard OpenTelemetry environment+variables:++```bash+OTEL_SERVICE_NAME=spree+OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318+```++That is the entire setup. Without an exporter configured, the gem stays+dormant and adds no overhead. `OTEL_SDK_DISABLED=true` turns telemetry off+regardless of any other setting.++Other standard variables work as documented in the+[OpenTelemetry SDK configuration reference](https://opentelemetry.io/docs/languages/sdk-configuration/),+including sampling:++```bash+# Sample 10% of traces (children follow their parent's decision)+OTEL_TRACES_SAMPLER=parentbased_traceidratio+OTEL_TRACES_SAMPLER_ARG=0.1+```++## What gets traced++Two layers combine into one trace per request or job.++**Framework spans** come from the official Rails auto-instrumentation: HTTP+requests, controller actions, database queries, background job enqueues and+executions, mail deliveries, and outbound HTTP calls. Trace context carries+across the job boundary, so work that happens in a background job stays+connected to the request that caused it.++**Commerce spans** come from Spree itself:++| Span | Kind | What it covers |+|---|---|---|+| `carts.complete` (any workflow key) | internal | One span per workflow run, with its outcome |+| `carts.complete process_payments` (any step) | internal / client | One span per workflow step; steps declared as external I/O become client spans |+| `carts.add_item hooks validate` | internal | Extension hook dispatch, only when handlers are registered |+| `order.placed dispatch` | internal | Event delivery to each subscriber, showing whether it ran inline or was enqueued |+| `spree.webhook.deliver order.placed` | client | Each webhook POST, with the destination host and response code |+| `spree.gateway.purchase` (any gateway action) | client | Each payment gateway call — authorize, purchase, capture, void, credit, and payment session operations |++A completed checkout, for example, produces one trace containing the HTTP+request, the `carts.complete` workflow and its steps, the payment gateway+call, the database work, and — linked from it — the background jobs and+webhook deliveries the order triggered.++Spree also propagates+[W3C Trace Context](https://www.w3.org/TR/trace-context/) headers on outbound+webhooks, so a system receiving your webhooks can join its own spans to the+trace that produced the event.++## Span attributes and personal data++Span attributes never contain personal or sensitive data. They are limited to+workflow and step names, gateway action names, payment method class names,+event names, webhook destination hosts, and HTTP status codes. Order contents,+customer emails, addresses, payment details, and webhook payloads are never+attached to spans.++## Metrics++Spree exports the trace signal. Request rates, error rates, and latency+percentiles per endpoint, workflow, or gateway are derived from spans in the+OpenTelemetry Collector with the+[span metrics connector](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/connector/spanmetricsconnector):++```yaml+# otel-collector config+connectors:+ spanmetrics:+ dimensions:+ - name: spree.workflow+ - name: spree.gateway.action++service:+ pipelines:+ traces:+ receivers: [otlp]+ exporters: [spanmetrics, otlp]+ metrics:+ receivers: [spanmetrics]+ exporters: [prometheusremotewrite]+```++## Using with Sentry++Sentry and OpenTelemetry are complementary — Sentry's error capture works+independently of tracing, so having both installed (as spree-starter does)+requires no special setup. For traces there are three arrangements:++**Sentry for errors, OpenTelemetry for traces (default).** Nothing to+configure. Just don't *also* enable Sentry's own performance tracing+(`traces_sample_rate`) — that would instrument every request twice and+produce two disconnected trace systems.++**Sentry as the trace backend.** Sentry ingests OpenTelemetry spans directly+through its [OTLP integration](https://docs.sentry.io/platforms/ruby/guides/rails/integrations/otlp/).+Order matters here: Sentry registers its span processor inside `Sentry.init`,+which only works if the OpenTelemetry SDK is already installed — so install+Spree's telemetry explicitly at the top of the same initializer:++```ruby+# Gemfile+gem 'sentry-opentelemetry'++# config/initializers/sentry.rb+SpreeOpenTelemetry.configure { |config| config.enabled = true }+SpreeOpenTelemetry.install!++Sentry.init do |config|+ config.dsn = ENV['SENTRY_DSN']+ config.otlp.enabled = true+ # Do not set traces_sample_rate or instrumenter — OpenTelemetry owns tracing.+end+```++```bash+# Sentry provides the exporter (derived from the DSN) — tell the SDK not to+# wire its own default OTLP exporter alongside it.+OTEL_TRACES_EXPORTER=none+```++A DSN alone does **not** enable tracing; `config.otlp.enabled` is the+explicit opt-in (Sentry bills for ingested spans, so error capture never+silently becomes span ingestion).++Spree's commerce spans — workflows, gateway calls, webhook deliveries — show+up in Sentry's trace view, and Sentry errors are linked automatically to the+span that was active when they were captured.++**Both, via the collector.** Point Spree at an OpenTelemetry Collector and+fan out from there — one pipeline exporting to your tracing backend and+another to Sentry's OTLP endpoint. This is the most flexible arrangement for+teams that want Grafana/Jaeger for latency work and Sentry for error triage+over the same traces.++## Correlating logs++To connect log lines to traces, tag your Rails logs with the current trace:++```ruby+# config/environments/production.rb+config.log_tags = [+ ->(_request) { "trace_id=#{OpenTelemetry::Trace.current_span.context.hex_trace_id}" }+]+```++## Trying it locally++Run Jaeger with an OTLP receiver and point Spree at it:++```bash+docker run --rm -p 16686:16686 -p 4318:4318 jaegertracing/jaeger:latest+```++```bash+OTEL_SERVICE_NAME=spree \+OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \+bin/rails server+```++Place a test order and open [http://localhost:16686](http://localhost:16686)+to see the trace.++## Code-level configuration++Everything routine is controlled by environment variables. A+`SpreeOpenTelemetry.configure` block exists for the rest — adding+instrumentation for libraries your app uses, removing a default, or advanced+SDK tuning:++```ruby+# config/initializers/opentelemetry.rb+SpreeOpenTelemetry.configure do |config|+ config.use 'OpenTelemetry::Instrumentation::Redis' # add an instrumentation+ config.skip 'OpenTelemetry::Instrumentation::ActionMailer' # remove a default+ config.with_sdk { |otel| otel.add_span_processor(my_processor) }+end+```++## Instrumenting your own code++Spree's spans are built on `ActiveSupport::Notifications`, and yours can be+too — or use the OpenTelemetry API directly:++```ruby+tracer = OpenTelemetry.tracer_provider.tracer('my_app')++tracer.in_span('loyalty.award_points', attributes: { 'loyalty.points' => 50 }) do+ # your code+end+```++Custom workflows get traced automatically: every `Spree::Workflow` run, step,+and hook dispatch is instrumented by the framework, including workflows your+application or extensions define.diff --git a/docs/developer/providers/overview.mdx b/docs/developer/providers/overview.mdxnew file mode 100644index 0000000000..0f62ef8ce8--- /dev/null+++ b/docs/developer/providers/overview.mdx@@ -0,0 +1,44 @@+---+title: Spree Fits Your Architecture+description: Spree is the commerce layer in the middle of the systems you already run — ERP, PIM, DAM, WMS, PSP, tax engines, search and identity connect through provider contracts, not forks.+---++Most mid-size and enterprise merchants do not start from zero. They run an ERP that owns stock, a PIM that owns product data, a DAM that owns media, a warehouse system that ships boxes, and a payment provider with years of history. Replacing all of that to adopt a commerce platform is not a migration — it is a rebuild nobody asked for.++Spree takes the opposite position: **it is the system of record for what the shopper sees, and your existing systems stay the system of record for what is true.** Content, prices and stock sync in and render from Spree's own copy; live calls to your systems happen only at decision moments — pricing a line, adding to cart, taking a stock hold, completing an order.++```mermaid+flowchart LR+ PIM[PIM] --> S+ ERP[ERP] --> S+ DAM[DAM] --> S+ subgraph S[Spree — commerce layer]+ API[Store & Admin APIs]+ end+ S --> WMS[WMS / carriers]+ S --> PSP[PSP]+ S --> TAX[Tax engine]+ S --> IDP[Identity provider]+ S --> APM[Observability / APM]+```++## The provider contracts++Every connection point is a documented contract with a default implementation that uses Spree's own data — a store that connects nothing works exactly as before.++| Your system | Spree contract | Guide |+|---|---|---|+| ERP (stock levels) | Inventory provider | [Connect your ERP](/developer/providers/erp) |+| PIM (product data, prices) | Pricing provider + data feeds | [Connect your PIM](/developer/providers/pim) |+| DAM (media) | Externally hosted media | [Product media & DAM](/developer/providers/dam) |+| WMS / 3PL / carriers | Fulfillment provider | [Shipping & WMS](/developer/providers/fulfillment) |+| Carrier rate shopping | Delivery rate provider | [Custom delivery rates](/developer/how-to/custom-delivery-rate-provider) |+| PSP | Payment gateway | [Custom payment method](/developer/how-to/custom-payment-method) |+| Tax engine | Tax provider | [Avalara](/integrations/tax/avalara) |+| Search | Search provider | [Custom search provider](/developer/how-to/custom-search-provider) |+| Identity provider (SSO) | OpenID Connect | [Identity & SSO](/developer/providers/sso) |+| APM / observability | OpenTelemetry | [Observability](/developer/providers/observability) |++## Credentials live in one place++Provider credentials are managed through Spree integrations — one admin surface for connecting external services, with secrets stored as masked preferences and connections verified before activation. Provider gems ship an integration class; there are no per-provider credential screens or environment-variable contracts for per-store services.diff --git a/docs/developer/providers/pim.mdx b/docs/developer/providers/pim.mdxnew file mode 100644index 0000000000..ef07b764ab--- /dev/null+++ b/docs/developer/providers/pim.mdx@@ -0,0 +1,27 @@+---+title: Connect Your PIM+description: Keep product data and pricing in your PIM. Spree syncs content in, renders from its own copy, and can price live from an external source at cart decision moments.+---++<Note>+This page documents functionality landing in an upcoming Spree 6.0 release. The interfaces described here may change before final release.+</Note>++Your PIM owns product content — names, descriptions, attributes, associations, prices. Spree renders the shopper-facing copy and asks your systems live only where a stale answer would cost money.++## Product data feeds++Products, variants and prices flow in through the Admin API and CSV imports. Feeds address records by the keys your PIM already uses via external references (`external:<system>:<id>`), so an integration never has to store Spree IDs to update what it created.++## The pricing provider++For merchants whose prices are computed elsewhere — contract pricing from an ERP, a pricing service, a PIM-driven price feed — a pricing provider answers price questions at cart decision moments with Spree's own price record shape. Tax-inclusive restatement and serializers keep working without knowing the number's origin.++Two properties of the contract matter for operations:++- **A provider declares a cache lifetime** and can decline anonymous browsing contexts, sending catalog pages straight to the local price resolver.+- **Pricing refuses on failure** rather than falling back — charging the wrong price is a dispute, not a retry.++## Price imports++Price lists and plain price updates load through CSV imports and the Admin API, writing history rather than silently overwriting — the audit trail shows what changed and when.diff --git a/docs/developer/providers/sso.mdx b/docs/developer/providers/sso.mdxnew file mode 100644index 0000000000..1d56851af6--- /dev/null+++ b/docs/developer/providers/sso.mdx@@ -0,0 +1,20 @@+---+title: Identity & SSO+description: Single sign-on with OpenID Connect is built into Spree — connect your existing identity provider for staff and customer authentication without custom code.+---++Enterprises already have an identity provider. Staff accounts live in it, security policy is enforced through it, and a commerce platform that demands its own password database is a liability. Spree 6 ships OpenID Connect support in core.++## Staff single sign-on++Connect your identity provider so back-office users sign in to the dashboard through your existing SSO — sessions, MFA and offboarding stay governed by the system your security team already operates.++## Customer authentication++Storefront customer authentication supports the same standards, so a merchant running a customer identity platform can keep it as the source of truth for shopper accounts.++## Bring your identity provider++Any OpenID Connect issuer works. This guide will walk through connecting the common ones and the configuration each needs.++For wiring a custom or non-OIDC JWT issuer into the Store and Admin APIs directly, see [integrating a third-party identity provider](/developer/how-to/custom-api-authentication).diff --git a/docs/developer/sdk/admin/extending.mdx b/docs/developer/sdk/admin/extending.mdxindex 73df7bfe88..146b70bbea 100644--- a/docs/developer/sdk/admin/extending.mdx+++ b/docs/developer/sdk/admin/extending.mdx@@ -66,5 +66,5 @@ The SDK transforms `filter`/`sort` into the Ransack-flavored query string the Ad## See also- The [Store SDK extending guide](/developer/sdk/extending) covers the same pattern for storefront endpoints — the API is identical, only the base path (`/api/v3/store`) and auth header differ.-- The [API](/developer/tutorial/api) and [SDK](/developer/tutorial/sdk) tutorials walk through creating new Spree endpoints end-to-end (Rails controller, serializer, TypeScript types). Everything they show for the Store API applies equivalently for the Admin API.+- The [API](/developer/tutorial/admin-api) and [SDK](/developer/tutorial/storefront) tutorials walk through creating new Spree endpoints end-to-end (Rails controller, serializer, TypeScript types). Everything they show for the Store API applies equivalently for the Admin API.- For building dashboard UI on top of your custom endpoint, see the [Dashboard](/developer/dashboard/overview) section — start with [Customization Quickstart](/developer/dashboard/customization/quickstart) for in-app changes or [Plugin Overview](/developer/dashboard/plugins/overview) for redistributable packages.diff --git a/docs/developer/sdk/admin/quickstart.mdx b/docs/developer/sdk/admin/quickstart.mdxindex b0f3f15d19..55cd0a0d57 100644--- a/docs/developer/sdk/admin/quickstart.mdx+++ b/docs/developer/sdk/admin/quickstart.mdx@@ -79,5 +79,5 @@ const page: PaginatedResponse<Order> = await client.orders.list()</CardGroup><Tip>- Adding your own resources? The [`spree generate api_resource`](/developer/tutorial/api) generator scaffolds Admin API endpoints (model, serializers, controllers, specs) in one command, and the [extending guide](/developer/sdk/extending) shows how to call custom endpoints from the SDK.+ Adding your own resources? The [`spree generate api_resource`](/developer/tutorial/admin-api) generator scaffolds Admin API endpoints (model, serializers, controllers, specs) in one command, and the [extending guide](/developer/sdk/extending) shows how to call custom endpoints from the SDK.</Tip>diff --git a/docs/developer/sdk/admin/resources.mdx b/docs/developer/sdk/admin/resources.mdxindex 5e58c9ce0b..264224a1a2 100644--- a/docs/developer/sdk/admin/resources.mdx+++ b/docs/developer/sdk/admin/resources.mdx@@ -125,4 +125,4 @@ await client.customFields('Spree::Product', 'prod_xxx').list()## Adding your own resources-The resource map grows with your store. The [`spree generate api_resource`](/developer/tutorial/api) generator scaffolds new Admin API endpoints (model, serializers, controllers, routes, specs) in one command — then call them from the SDK with a [custom fetch or raw request](/developer/sdk/extending), or generate a typed client for them.+The resource map grows with your store. The [`spree generate api_resource`](/developer/tutorial/admin-api) generator scaffolds new Admin API endpoints (model, serializers, controllers, routes, specs) in one command — then call them from the SDK with a [custom fetch or raw request](/developer/sdk/extending), or generate a typed client for them.diff --git a/docs/developer/sdk/extending.mdx b/docs/developer/sdk/extending.mdxindex 52ed0031f0..8bb92735d2 100644--- a/docs/developer/sdk/extending.mdx+++ b/docs/developer/sdk/extending.mdx@@ -30,4 +30,4 @@ const nike = await client.request<Brand>('GET', '/brands/nike')`client.request` uses the same auth headers, retry logic, and locale/currency defaults as `client.products.list()` or any other built-in resource.-For a complete walkthrough — creating the API endpoints on the backend, defining TypeScript types, filtering, and expanding associations — see the [API](/developer/tutorial/api) and [SDK](/developer/tutorial/sdk) tutorials.+For a complete walkthrough — creating the API endpoints on the backend, defining TypeScript types, filtering, and expanding associations — see the [API](/developer/tutorial/admin-api) and [SDK](/developer/tutorial/storefront) tutorials.diff --git a/docs/developer/tutorial/admin-api.mdx b/docs/developer/tutorial/admin-api.mdxnew file mode 100644index 0000000000..934f28a4f4--- /dev/null+++ b/docs/developer/tutorial/admin-api.mdx@@ -0,0 +1,13 @@+---+title: Admin API+description: Add a ProductFaq endpoint to the Admin API — resource controller conventions, an admin serializer, and a permission catalog entry.+---++Staff manage FAQs through the Admin API — the same API the dashboard, integrations and scripts use. This chapter adds the endpoint following the conventions every Spree resource follows, which is what makes the dashboard plugin in the next chapter nearly free.++## What this chapter covers++- The resource controller: full CRUD from one small controller declaring its model, serializer and permitted attributes+- The admin serializer and prefixed IDs+- Registering the resource in the permission catalog so roles and API key scopes cover it+- Exercising the endpoint with the Admin CLIdiff --git a/docs/developer/tutorial/dashboard-plugin.mdx b/docs/developer/tutorial/dashboard-plugin.mdxnew file mode 100644index 0000000000..2036714bcd--- /dev/null+++ b/docs/developer/tutorial/dashboard-plugin.mdx@@ -0,0 +1,14 @@+---+title: Dashboard Plugin+description: Scaffold a dashboard plugin for ProductFaqs — a table, a form, and navigation, generated by the CLI and wired to the Admin API endpoint.+---++With the Admin API in place, the back-office UI is a dashboard plugin: a table listing FAQs, a form to create and edit them, and a navigation entry — scaffolded by the CLI and customized from there.++## What this chapter covers++- Scaffolding the plugin with the CLI+- The resource table: columns, search and pagination against the Admin API+- The form: fields, validation errors mapped from API responses+- Registering navigation and permissions-aware visibility+- Running it against your development storediff --git a/docs/developer/tutorial/events.mdx b/docs/developer/tutorial/events.mdxindex 32d57b9de0..4150489433 100644--- a/docs/developer/tutorial/events.mdx+++ b/docs/developer/tutorial/events.mdx@@ -1,172 +1,12 @@----title: Events & Webhooks-description: React to Spree store activity and connect to external systems like an OMS, warehouse, or ERP using event subscribers, the subscriber generator, and webhooks.+title: Events+description: Publish lifecycle events for FAQs and react to them — subscribers inside the app, webhooks for systems outside it.----<Info>- This guide assumes you've completed the [Model](/developer/tutorial/model) and [API](/developer/tutorial/api) tutorials — we'll reuse the Brand serializer created there.-</Info>+Features rarely live alone — something usually needs to know when data changes. This chapter publishes lifecycle events for FAQs and consumes them both ways.-Almost every real store talks to other systems: an order management system (OMS), a warehouse (WMS), an ERP, a CRM, a marketing platform. In Spree, the integration surface is the **events system** — models publish events as things happen, and you react to them without touching core code.+## What this chapter covers-There are two ways to consume events, and they serve different audiences:--| Mechanism | Code lives | Best for |-|---|---|---|-| **Subscriber** | In your Spree app | Calling external APIs with your own client code, internal side effects, anything needing app context |-| **Webhook** | In the external system | Letting a third party receive HTTP callbacks — no Ruby in your app, endpoints managed from the admin |--We'll do both: push completed orders to an OMS with a subscriber, give the Brand model its own lifecycle events, and set up an outbound webhook.--## Step 1: Subscribe to a Core Event--When an order completes, send it to the OMS. Generate a subscriber:--<CodeGroup>--```bash Spree CLI (Docker)-spree generate subscriber OmsOrderSync order.completed-```--```bash Without Spree CLI-bin/rails g spree:subscriber OmsOrderSync order.completed-```--</CodeGroup>--This creates the subscriber, a spec stub, and — crucially — **registers it** in `config/initializers/spree.rb` (injected into the existing `after_initialize` block every Spree app ships with). Subscribers are not auto-discovered; a subscriber that never gets appended to `Spree.subscribers` is a silent no-op, which is why the generator owns that step (re-runs are idempotent, and each new subscriber appends to the same initializer).--Fill in the handler:--```ruby app/subscribers/oms_order_sync_subscriber.rb-class OmsOrderSyncSubscriber < Spree::Subscriber- subscribes_to 'order.completed'-- def handle(event)- order = Spree::Order.find_by_prefix_id(event.payload['id'])- return unless order-- OmsClient.create_order(- number: order.number,- email: order.email,- line_items: order.line_items.map { |li| { sku: li.sku, quantity: li.quantity } }- )- end-end-```--Two things worth understanding:--- **Payloads carry prefixed IDs**, not raw database IDs — always look records up with `find_by_prefix_id`. The payload itself is the resource serialized with its v3 API serializer, so `event.payload['number']`, `['email']`, etc. are available directly when you don't need the full record.-- **Subscribers run async by default** — each `handle` call is an ActiveJob on the events queue, so a slow OMS API never blocks checkout. Pass `subscribes_to 'order.completed', async: false` only when you genuinely need synchronous execution.--Restart the server, complete a test order, and watch the job fire (`spree logs worker` — or your job backend's UI).--## Step 2: Give Brand Its Own Lifecycle Events--Core models like Payment and Shipment publish `*.created` / `*.updated` / `*.deleted` events automatically. Your models can too — add one line to the Brand model:--```ruby app/models/spree/brand.rb {3}-module Spree- class Brand < Spree.base_class- publishes_lifecycle_events-- # ... existing code ...- end-end-```--Now `brand.created`, `brand.updated`, and `brand.deleted` fire after the matching transactions commit — and because you created `Spree::Api::V3::BrandSerializer` in the [API step](/developer/tutorial/api), the payloads automatically use it (the events system resolves the serializer by naming convention). Anyone — subscriber or webhook — can react to brand changes with the same JSON shape your API serves.--<CodeGroup>--```bash Spree CLI (Docker)-spree generate subscriber BrandSync brand.created brand.updated-```--```bash Without Spree CLI-bin/rails g spree:subscriber BrandSync brand.created brand.updated-```--</CodeGroup>--```ruby app/subscribers/brand_sync_subscriber.rb-class BrandSyncSubscriber < Spree::Subscriber- subscribes_to 'brand.created', 'brand.updated'-- def handle(event)- SearchIndexer.upsert_brand(event.payload)- end-end-```--## Step 3: Publish a Custom Event--Lifecycle events cover persistence; custom events express *domain* moments. Say featuring a brand should notify the marketing platform:--```ruby-brand.publish_event('brand.featured')-```--The payload defaults to the serializer output; pass your own hash as the second argument when the event needs different data. Subscribers consume it like any other event name.--## Step 4: Outbound Webhooks — No Code Required--When the consumer is an external system you don't deploy code into, use webhooks. In the admin, go to **Settings → Webhooks**, add an endpoint with the destination URL, and pick the events to deliver — `order.completed`, `brand.created`, anything publishing in your store. The endpoint's **signing secret is shown once on creation** — store it in the receiving system.--Each delivery is an HTTP POST with this envelope:--```json-{- "id": "550e8400-e29b-41d4-a716-446655440000",- "name": "order.completed",- "created_at": "2026-06-11T12:00:00Z",- "data": { "id": "or_m3Rp9wXz", "number": "R123456789", "...": "..." },- "metadata": {}-}-```--And three headers the receiver should use:--| Header | Contents |-|---|---|-| `X-Spree-Webhook-Event` | The event name |-| `X-Spree-Webhook-Timestamp` | Unix timestamp of the delivery |-| `X-Spree-Webhook-Signature` | `HMAC-SHA256(secret, "{timestamp}.{body}")` |--Verify the signature before trusting a payload:--```ruby-def verified?(request, secret)- timestamp = request.headers['X-Spree-Webhook-Timestamp']- expected = OpenSSL::HMAC.hexdigest('SHA256', secret, "#{timestamp}.#{request.raw_post}")- ActiveSupport::SecurityUtils.secure_compare(expected, request.headers['X-Spree-Webhook-Signature'])-end-```--Delivery semantics to design around: failed deliveries (timeouts, connection errors, non-2xx responses) are **recorded, not retried automatically** — redeliver from the endpoint's delivery history in the admin, or via `POST /api/v3/admin/webhook_endpoints/:webhook_endpoint_id/deliveries/:id/redeliver`. After **15 consecutive failures** the endpoint auto-disables and store staff get an email; a successful delivery resets the counter.--## Testing a Subscriber--Subscribers are plain Ruby — test `handle` directly with a constructed event:--```ruby spec/subscribers/oms_order_sync_subscriber_spec.rb-require 'rails_helper'--RSpec.describe OmsOrderSyncSubscriber do- it 'pushes completed orders to the OMS' do- order = create(:completed_order_with_totals)- event = Spree::Event.new(name: 'order.completed', payload: { 'id' => order.prefixed_id })-- expect(OmsClient).to receive(:create_order).with(hash_including(number: order.number))-- described_class.new.handle(event)- end-end-```--## Related Documentation--- [Events](/developer/core-concepts/events) — the full event catalog, subscriber DSL, and delivery guarantees-- [Webhooks](/developer/core-concepts/webhooks) — endpoint management, security, and the per-event payload schemas-- [Extending Core Models](/developer/tutorial/extending-models) — when a decorator is the right tool instead+- Publishing lifecycle events from the model+- A subscriber reacting inside the application+- Delivering the event to an external system as a webhookdiff --git a/docs/developer/tutorial/introduction.mdx b/docs/developer/tutorial/introduction.mdxindex 6cd9f4170d..5d7975cdb8 100644--- a/docs/developer/tutorial/introduction.mdx+++ b/docs/developer/tutorial/introduction.mdx@@ -1,63 +1,24 @@----title: Tutorial-sidebarTitle: Introduction-description: Build a complete custom Brands feature in Spree — model, admin UI, Store and Admin APIs, events, and TypeScript storefront integration — end to end.+title: "Tutorial: Build a Custom Feature"+description: Build Product FAQs end to end — a custom model, an Admin API endpoint, a dashboard plugin, a Store API endpoint, and storefront rendering through the TypeScript SDK.----This tutorial walks you through creating a complete Spree feature from scratch: a "Brands" feature that lets admins manage [Product](/developer/core-concepts/products) brands, exposes them through the Store API, and consumes them from TypeScript.+This tutorial builds one complete feature — **Product FAQs**, questions and answers attached to products — through every layer of a Spree 6 application. By the end you will have a custom model, back-office management in the dashboard, and customer-facing display on the storefront.-It's written for **both backend and frontend developers**. The Ruby you'll write is minimal and mostly generated — Spree's generators produce convention-correct models, admin UIs, and API endpoints, and the TypeScript SDK gives you typed access from your storefront. You don't need to be a Rails expert to follow along.+## The two tracks-## Before you start--You need a running Spree app. The fastest path is [create-spree-app](/developer/create-spree-app/quickstart) — a Docker-based project with the [Spree CLI](/developer/cli/quickstart), no local Ruby required:--```bash-npx create-spree-app@latest my-store-```--An existing app with Spree gems works just as well. **Every command in this tutorial is shown in two forms** — **Spree CLI** (runs inside Docker) and **Without Spree CLI** (runs directly on your machine) — pick the tab that matches your setup and ignore the other.+The tutorial is organized so you only build what your feature needs:-<Note>- **create-spree-app projects:** run `spree eject` once before starting. Fresh projects use a prebuilt Docker image; ejecting switches to the dev setup that mounts `backend/` into the container, so the files the generators create land in your project (and reload live as you edit them).-</Note>+| Track | Chapters | Build this when |+|---|---|---|+| Foundation | [Model](/developer/tutorial/model) | Always |+| **A — manage it in the dashboard** | [Admin API](/developer/tutorial/admin-api) → [Dashboard plugin](/developer/tutorial/dashboard-plugin) | The feature is operated by staff — internal tooling, back-office data |+| **B — expose it on the storefront** | [Store API](/developer/tutorial/store-api) → [Storefront](/developer/tutorial/storefront) | Customers see the feature |+| Finishing | [Events](/developer/tutorial/events) → [Testing](/developer/tutorial/testing) | Always |-<Tip>- Using an AI coding agent? Install the [Spree agent skills](/developer/agentic/agent-skills) (`npx skills add spree/agent-skills`) and connect the [docs MCP server](/developer/agentic/mcp) before starting — your agent will know the conventions this tutorial teaches and can follow along with you. See [Agentic Development](/developer/agentic/overview).-</Tip>+An internal tool is Track A alone. A storefront feature over existing data is Track B alone. Product FAQs need both: staff write the answers, customers read them.-## What you'll build--* A `Brand` model with a rich text description and an uploadable logo — one generator command-* An admin UI for managing brands — one generator command, then customized-* A `brand` association on Products, surfaced in the product admin form-* Store API endpoints (`GET /api/v3/store/brands`) with serializers and prefixed IDs-* Typed TypeScript access to brands from your storefront via `@spree/sdk`-* Event subscribers and webhooks connecting the store to external systems-* Automated tests for all of it--## Tutorial Sections+## Before you start-<CardGroup cols={2}>- <Card title="1. Model" icon="database" href="/developer/tutorial/model">- Generate the Brand model — columns, rich text description, and logo upload in one command- </Card>- <Card title="2. Admin Dashboard" icon="gauge" href="/developer/tutorial/admin">- Scaffold the admin UI, then add the description editor, logo upload, and table columns- </Card>- <Card title="3. Extending Core Models" icon="plug" href="/developer/tutorial/extending-models">- Connect Brands to Products using a decorator and an association- </Card>- <Card title="4. API" icon="code" href="/developer/tutorial/api">- Expose Brands through the Store and Admin APIs — generated in one command, or hand-built to learn the pieces- </Card>- <Card title="5. Events & Webhooks" icon="zap" href="/developer/tutorial/events">- React to store activity and connect external systems — OMS, warehouse, ERP- </Card>- <Card title="6. SDK" icon="js" href="/developer/tutorial/sdk">- Consume Brand endpoints from TypeScript using the SDK- </Card>- <Card title="7. Testing" icon="flask-vial" href="/developer/tutorial/testing">- Write automated tests for your feature- </Card>-</CardGroup>+- A running Spree application — see the [quickstart](/developer/getting-started/quickstart)+- The AI tooling set up — the [agent skills and MCP server](/developer/agentic/overview) make every step of this tutorial fasterdiff --git a/docs/developer/tutorial/model.mdx b/docs/developer/tutorial/model.mdxindex 59ca8588f3..2463c8c06d 100644--- a/docs/developer/tutorial/model.mdx+++ b/docs/developer/tutorial/model.mdx@@ -1,116 +1,13 @@---title: Model-description: Create a custom Brand model in Spree with database columns, a rich text description, and an Active Storage logo upload using a single generator command.+description: Generate the ProductFaq model — migration, associations, validations and store scoping — the foundation both tracks build on.----<Note>- This is a backend customization. You need to perform it in the `backend` directory if you used `create-spree-app` to set up your Spree application.-</Note>+Every feature starts with a model. This chapter generates `ProductFaq` — question, answer, position, attached to a product and scoped to the store.-In this step we'll create the `Spree::Brand` model with everything it needs: a `name` column, a rich text `description`, and an uploadable `logo`.+## What this chapter covers-## Step 1: Generate the Model--Spree ships a `spree:model` generator that produces a model and migration following all Spree conventions — `Spree::` namespacing, prefixed IDs, presence validations, and API filtering allowlists. It understands Rails attribute types including the virtual ones, so rich text and file attachments are part of the same command:--<CodeGroup>--```bash Spree CLI (Docker)-spree generate model Brand name:string:index description:rich_text logo:attachment-```--```bash Without Spree CLI-bin/rails g spree:model Brand name:string:index description:rich_text logo:attachment-```--</CodeGroup>--<Info>- Throughout this tutorial every command is shown in two forms. **Spree CLI** is for projects created with [create-spree-app](/developer/create-spree-app/quickstart), where the app runs in Docker and `spree <command>` routes into the container. **Without Spree CLI** is for apps running Spree backend directly on your machine.-</Info>--This creates two files:--- `app/models/spree/brand.rb` — the model-- `db/migrate/XXXXXXXXXXXXXX_create_spree_brands.rb` — the migration--Now apply the migration:--<CodeGroup>--```bash Spree CLI (Docker)-spree migrate-```--```bash Without Spree CLI-bin/rails db:migrate-```--</CodeGroup>--This creates the `spree_brands` table with an indexed `name` column. The `description` and `logo` attributes don't add columns — rich text lives in Action Text's `action_text_rich_texts` table, and uploads live in Active Storage's tables.--## Step 2: Understand the Generated Model--Open `app/models/spree/brand.rb`:--```ruby app/models/spree/brand.rb-module Spree- class Brand < Spree.base_class- has_prefix_id :brand-- has_rich_text :description- has_one_attached :logo-- validates :name, presence: true-- self.whitelisted_ransackable_attributes = %w[name]- self.whitelisted_ransackable_associations = %w[]- self.whitelisted_ransackable_scopes = %w[]- end-end-```--Line by line:--- **`Spree.base_class`** — inherits all Spree model functionality (multi-store scoping helpers, preferences, and more). The class is namespaced under `Spree::`, so it's available as `Spree::Brand`.-- **`has_prefix_id :brand`** — records get Stripe-style public IDs like `brand_k5nR8xLq`. APIs never expose raw database IDs.-- **`has_rich_text :description`** — formatted content via [Action Text](https://guides.rubyonrails.org/action_text_overview.html).-- **`has_one_attached :logo`** — file uploads via [Active Storage](https://guides.rubyonrails.org/active_storage_overview.html), with image processing and direct-to-storage uploads.-- **`validates :name, presence: true`** — generated automatically for required columns.-- **`whitelisted_ransackable_attributes`** — controls which attributes API clients may filter and sort by. Only allowlisted attributes are queryable, so adding `name` here is what later makes `?q[name_cont]=nike` work.--## Step 3: Try It in the Console--<CodeGroup>--```bash Spree CLI (Docker)-spree console-```--```bash Without Spree CLI-bin/rails console-```--</CodeGroup>--```ruby-brand = Spree::Brand.create!(name: "Wilson")-brand.prefixed_id # => "brand_k5nR8xLq"--brand.update!(description: "<h1>Hello</h1><p>World</p>")-brand.description.to_s # => rendered rich text HTML-brand.description.to_plain_text # => "Hello World"--Spree::Brand.find_by_prefix_id!("brand_k5nR8xLq") # lookup by public ID-```--We'll upload the logo through the admin UI in the next step — the model side is already done.--<Tip>- The generator accepts more attribute types and options — references with auto-resolved class names (`user:belongs_to`), unique indexes (`slug:string:uniq`), soft delete (`--paranoid`), and custom fields support (`--metafields`). Run it with `--help` to see everything.-</Tip>--## Next Step--The model is complete. Now let's give admins a UI to manage brands: [Admin Dashboard](/developer/tutorial/admin).+- Generating the model and migration from the command line+- Store scoping — why every store-owned record belongs to a store, and what that buys you+- The association to products, validations, and ordering+- Running the migration and creating a record in the consolediff --git a/docs/developer/tutorial/store-api.mdx b/docs/developer/tutorial/store-api.mdxnew file mode 100644index 0000000000..cd4123747c--- /dev/null+++ b/docs/developer/tutorial/store-api.mdx@@ -0,0 +1,13 @@+---+title: Store API+description: Expose FAQs to customers — a read-only Store API endpoint with a serializer that shows only what shoppers should see.+---++Customers read FAQs through the Store API. This chapter adds the customer-facing endpoint — read-only, scoped to the current store, with a serializer deliberately smaller than the admin one.++## What this chapter covers++- The store resource controller: read-only by default, and why+- The store serializer: public fields only — no timestamps, no internal data+- Scoping: only FAQs for purchasable products of the current store+- Nesting under the product endpointdiff --git a/docs/developer/tutorial/storefront.mdx b/docs/developer/tutorial/storefront.mdxnew file mode 100644index 0000000000..72e64af4ad--- /dev/null+++ b/docs/developer/tutorial/storefront.mdx@@ -0,0 +1,12 @@+---+title: Storefront+description: Render FAQs on the product page — regenerate the SDK types, extend the TypeScript client, and build the component in the Next.js storefront.+---++The Store API endpoint becomes typed TypeScript and a component on the product page. This chapter closes the loop from Rails model to customer screen.++## What this chapter covers++- The type generation pipeline: serializer to TypeScript types to runtime schemas+- Extending the SDK client with the new resource+- Fetching and rendering FAQs on the product detail page in the Next.js storefrontdiff --git a/docs/developer/tutorial/testing.mdx b/docs/developer/tutorial/testing.mdxindex 80a650c661..45a45a8f2f 100644--- a/docs/developer/tutorial/testing.mdx+++ b/docs/developer/tutorial/testing.mdx@@ -1,729 +1,13 @@---title: Testing-description: Write automated tests for the Brands tutorial feature using RSpec, Factory Bot, and Capybara, plus helpers from the spree_dev_tools gem.+description: Test the feature at every layer — model and request specs with RSpec, dashboard plugin tests with Vitest, and an end-to-end check with Playwright.----Automated testing is a crucial part of the development process. It helps you ensure that your code works as expected and catches bugs early.-Spree uses [RSpec](https://rspec.info), [Factory Bot](https://github.com/thoughtbot/factory_bot_rails), and [Capybara](https://github.com/teamcapybara/capybara) for testing.-We also provide the `spree_dev_tools` gem that helps you write Spree-specific tests.+Each layer of the feature gets the test that suits it: fast Ruby specs for the model and both API endpoints, component tests for the plugin, and one end-to-end pass proving the whole path works.-<Info>- This guide assumes you've completed all previous tutorials through [API](/developer/tutorial/api). You should have a complete `Spree::Brand` model with admin features and API endpoints.-</Info>+## What this chapter covers-## Setup--**If your app came from [create-spree-app](/developer/create-spree-app/quickstart) or [spree-starter](https://github.com/spree/spree-starter), the test environment is already set up** — RSpec, Factory Bot, Capybara, DatabaseCleaner, and the `spree_dev_tools` helpers (`stub_authorization!`, the `'API v3 Store'` shared context, Spree factories) ship preconfigured in `spec/support/`. Skip to creating the fixtures file below.--<Accordion title="Setting up an app that doesn't have RSpec yet">--For an existing Rails app without test setup, install RSpec and the Spree test helpers:--<CodeGroup>--```bash Spree CLI (Docker)-spree generate rspec:install-spree generate spree_dev_tools:install-```--```bash Without Spree CLI-bin/rails g rspec:install-bin/rails g spree_dev_tools:install-```--</CodeGroup>--The `spree_dev_tools` generator adds the Spree-specific helpers to `spec/support/`: authorization helpers (`stub_authorization!`), Factory Bot configuration, Capybara setup for feature tests, and more.--</Accordion>--### Create the Fixtures Directory and File--When writing tests that involve file attachments (like images, PDFs, etc.), you need fixture files that your factories can use. Here's how to set them up.--```bash-mkdir -p spec/fixtures/files && printf '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82' > spec/fixtures/files/logo.png-```--### What the generators already created--If you used `spree generate api_resource` in the [API step](/developer/tutorial/api), you already have controller specs (`spec/controllers/spree/api/v3/store/brands_controller_spec.rb` and `…/admin/brands_controller_spec.rb`) and a factory (`spec/factories/spree/brand_factory.rb`). The sections below build the same things by hand — compare as you go, and keep whichever you prefer.--For the model spec, create `spec/models/spree/brand_spec.rb` — we'll fill it in below.--## Writing Factories--Factories provide a convenient way to create test data. Create a factory for your Brand model:--```ruby spec/factories/spree/brand_factory.rb-FactoryBot.define do- factory :brand, class: Spree::Brand do- sequence(:name) { |n| "Brand #{n}" }- sequence(:slug) { |n| "brand-#{n}" }-- trait :with_description do- description { '<div>A great brand for <strong>quality products</strong></div>' }- end-- trait :with_logo do- after(:create) do |brand|- brand.logo.attach(- io: File.new(Rails.root.join('spec', 'fixtures', 'files', 'logo.png')),- filename: 'logo.png'- )- end- end-- trait :with_products do- transient do- products_count { 3 }- store { nil }- end-- after(:create) do |brand, evaluator|- store = evaluator.store || create(:store)- create_list(:product, evaluator.products_count, brand: brand)- end- end- end-end-```--### Factory Usage Examples--```ruby-# Basic factory-brand = create(:brand)--# With traits-brand = create(:brand, :with_description, :with_logo)--# With custom attributes-brand = create(:brand, name: 'Nike')--# Build without persisting (faster for unit tests)-brand = build(:brand)--# Create multiple records-brands = create_list(:brand, 5)--# With associated products-brand = create(:brand, :with_products)-brand = create(:brand, :with_products, products_count: 5)-```--## Writing Model Tests--Model tests verify your business logic, validations, associations, and scopes.--```ruby spec/models/spree/brand_spec.rb-require 'rails_helper'--RSpec.describe Spree::Brand, type: :model do- describe 'associations' do- it 'has many products' do- association = described_class.reflect_on_association(:products)- expect(association.macro).to eq(:has_many)- expect(association.class_name).to eq('Spree::Product')- end- end-- describe 'validations' do- it 'validates presence of name' do- brand = build(:brand, name: nil)- expect(brand).not_to be_valid- expect(brand.errors[:name]).to include("can't be blank")- end-- describe 'slug uniqueness' do- let!(:existing_brand) { create(:brand, slug: 'nike') }-- it 'validates uniqueness of slug' do- brand = build(:brand, slug: 'nike')- expect(brand).not_to be_valid- expect(brand.errors[:slug]).to include('has already been taken')- end- end- end-- describe 'FriendlyId' do- it 'generates slug from name' do- brand = create(:brand, name: 'Nike Sportswear', slug: nil)- expect(brand.slug).to eq('nike-sportswear')- end-- it 'handles duplicate names by appending UUID' do- create(:brand, name: 'Nike', slug: 'nike')- brand = create(:brand, name: 'Nike', slug: nil)- expect(brand.slug).to match(/nike-[a-f0-9-]+/)- end- end-- describe '#image' do- let(:brand) { create(:brand, :with_logo) }-- it 'returns logo as image for Open Graph' do- expect(brand.image).to eq(brand.logo)- end- end-end-```--### Testing Decorators--When you extend core Spree models with decorators (see [Extending Core Models](/developer/tutorial/extending-models)), test the added functionality:--```ruby spec/models/spree/product_decorator_spec.rb-require 'rails_helper'--RSpec.describe 'Spree::Product brand association' do- let(:store) { @default_store }- let(:brand) { create(:brand) }- let(:product) { create(:product) }-- describe 'brand association' do- it 'can be assigned a brand' do- product.brand = brand- product.save!-- expect(product.reload.brand).to eq(brand)- end-- it 'is optional' do- product.brand = nil- expect(product).to be_valid- end- end-- describe 'brand.products' do- let!(:product1) { create(:product, brand: brand) }- let!(:product2) { create(:product, brand: brand) }- let!(:other_product) { create(:product) }-- it 'returns products for the brand' do- expect(brand.products).to contain_exactly(product1, product2)- end-- it 'nullifies brand_id when brand is destroyed' do- brand.destroy- expect(product1.reload.brand_id).to be_nil- end- end-end-```--## Writing Controller Tests--Controller tests verify that your endpoints respond correctly and perform the expected actions.--### Store API Controller Tests--Test the API endpoints we created in the [API tutorial](/developer/tutorial/api). Store API tests use the `'API v3 Store'` shared context which sets up a store, publishable API key, and JWT tokens — it ships in the `spree_api` gem, so require `spree/api/testing_support/v3/base` at the top of the spec.--```ruby spec/controllers/spree/api/v3/store/brands_controller_spec.rb-require 'rails_helper'-require 'spree/api/testing_support/v3/base'--RSpec.describe Spree::Api::V3::Store::BrandsController, type: :controller do- render_views-- include_context 'API v3 Store'-- let!(:brand1) { create(:brand, name: 'Nike') }- let!(:brand2) { create(:brand, name: 'Adidas') }-- before do- request.headers['X-Spree-Api-Key'] = api_key.token- end-- describe 'GET #index' do- it 'returns a list of brands' do- get :index-- expect(response).to have_http_status(:ok)- expect(json_response['data'].size).to eq(2)- end-- it 'returns brand attributes' do- get :index-- brand_data = json_response['data'].first- expect(brand_data).to include('id', 'name', 'slug')- end-- it 'returns prefixed IDs' do- get :index-- ids = json_response['data'].map { |b| b['id'] }- ids.each { |id| expect(id).to start_with('brand_') }- end-- it 'returns pagination metadata' do- get :index, params: { page: 1, limit: 1 }-- expect(json_response['data'].size).to eq(1)- expect(json_response['meta']).to include(- 'page' => 1,- 'limit' => 1,- 'count' => 2,- 'pages' => 2- )- end-- it 'filters by name' do- get :index, params: { q: { name_cont: 'nik' } }-- expect(json_response['data'].size).to eq(1)- expect(json_response['data'].first['name']).to eq('Nike')- end-- it 'sorts by name' do- get :index, params: { sort: 'name' }-- names = json_response['data'].map { |b| b['name'] }- expect(names).to eq(%w[Adidas Nike])- end- end-- describe 'GET #show' do- it 'returns a brand by prefixed ID' do- get :show, params: { id: brand1.prefixed_id }-- expect(response).to have_http_status(:ok)- expect(json_response['id']).to eq(brand1.prefixed_id)- expect(json_response['name']).to eq('Nike')- end-- it 'returns a brand by slug' do- get :show, params: { id: brand1.slug }-- expect(response).to have_http_status(:ok)- expect(json_response['name']).to eq('Nike')- end-- it 'returns 404 for non-existent brand' do- get :show, params: { id: 'brand_nonexistent' }-- expect(response).to have_http_status(:not_found)- end- end-- describe 'GET #show with logo' do- let!(:brand_with_logo) { create(:brand, :with_logo) }-- it 'includes logo_url when logo is attached' do- get :show, params: { id: brand_with_logo.prefixed_id }-- expect(json_response['logo_url']).to be_present- end- end-end-```--### Testing the Product Brand Association--Test that the custom Product serializer includes brand data:--```ruby spec/controllers/spree/api/v3/store/products_brand_spec.rb-require 'rails_helper'-require 'spree/api/testing_support/v3/base'--RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do- render_views-- include_context 'API v3 Store'-- let(:brand) { create(:brand, name: 'Nike') }- let!(:product) { create(:product, brand: brand, status: 'active') }-- before do- request.headers['X-Spree-Api-Key'] = api_key.token- end-- describe 'GET #show' do- it 'includes brand_id' do- get :show, params: { id: product.prefixed_id }-- expect(json_response['brand_id']).to eq(brand.prefixed_id)- end-- it 'does not include brand object without expand' do- get :show, params: { id: product.prefixed_id }-- expect(json_response).not_to have_key('brand')- end-- it 'includes brand object with expand=brand' do- get :show, params: { id: product.prefixed_id, expand: 'brand' }-- expect(json_response['brand']).to be_present- expect(json_response['brand']['id']).to eq(brand.prefixed_id)- expect(json_response['brand']['name']).to eq('Nike')- end- end-- describe 'GET #index' do- it 'filters products by brand_id' do- other_product = create(:product, status: 'active')-- get :index, params: { q: { brand_id_eq: brand.id } }-- ids = json_response['data'].map { |p| p['id'] }- expect(ids).to include(product.prefixed_id)- expect(ids).not_to include(other_product.prefixed_id)- end- end-end-```--### Admin Controller Tests--```ruby spec/controllers/spree/admin/brands_controller_spec.rb-require 'rails_helper'--RSpec.describe Spree::Admin::BrandsController, type: :controller do- stub_authorization!- render_views-- describe 'GET #index' do- let!(:brand1) { create(:brand, name: 'Adidas') }- let!(:brand2) { create(:brand, name: 'Nike') }-- it 'returns a successful response' do- get :index- expect(response).to be_successful- end-- it 'displays all brands' do- get :index- expect(response.body).to include('Adidas')- expect(response.body).to include('Nike')- end- end-- describe 'GET #new' do- it 'returns a successful response' do- get :new- expect(response).to be_successful- end-- it 'displays the new brand form' do- get :new- expect(response.body).to include('brand[name]')- end- end-- describe 'POST #create' do- context 'with valid params' do- let(:valid_params) do- { brand: { name: 'New Brand' } }- end-- it 'creates a new brand' do- expect {- post :create, params: valid_params- }.to change(Spree::Brand, :count).by(1)- end-- it 'redirects to the edit page' do- post :create, params: valid_params- expect(response).to redirect_to(spree.edit_admin_brand_path(Spree::Brand.last))- end- end-- context 'with invalid params' do- let(:invalid_params) do- { brand: { name: '' } }- end-- it 'does not create a new brand' do- expect {- post :create, params: invalid_params- }.not_to change(Spree::Brand, :count)- end-- it 'returns unprocessable entity status' do- post :create, params: invalid_params- expect(response).to have_http_status(:unprocessable_content)- end- end- end-- describe 'GET #edit' do- let(:brand) { create(:brand) }-- it 'returns a successful response' do- get :edit, params: { id: brand.id }- expect(response).to be_successful- end- end-- describe 'PUT #update' do- let(:brand) { create(:brand, name: 'Old Name') }-- context 'with valid params' do- it 'updates the brand' do- put :update, params: { id: brand.id, brand: { name: 'New Name' } }- expect(brand.reload.name).to eq('New Name')- end-- it 'redirects to the edit page' do- put :update, params: { id: brand.id, brand: { name: 'New Name' } }- expect(response).to redirect_to(spree.edit_admin_brand_path(brand))- end- end- end-- describe 'DELETE #destroy' do- let!(:brand) { create(:brand) }-- it 'removes the brand from the database' do- expect {- delete :destroy, params: { id: brand.id }, format: :html- }.to change(Spree::Brand, :count).by(-1)- end- end-end-```--## Writing Feature Tests--Feature tests (also called system tests) simulate real user interactions using Capybara.--### Admin Feature Tests--```ruby spec/features/spree/admin/brands_spec.rb-require 'rails_helper'--RSpec.feature 'Admin Brands', type: :feature do- stub_authorization!-- describe 'listing brands' do- let!(:brand1) { create(:brand, name: 'Nike') }- let!(:brand2) { create(:brand, name: 'Adidas') }-- it 'displays all brands' do- visit spree.admin_brands_path-- expect(page).to have_content('Nike')- expect(page).to have_content('Adidas')- end- end-- describe 'creating a brand' do- it 'creates a new brand successfully' do- visit spree.admin_brands_path- click_on 'New Brand'-- fill_in 'Name', with: 'Puma'- fill_in 'Slug', with: 'puma'-- click_on 'Create'- wait_for_turbo-- expect(page).to have_content('Brand "Puma" has been successfully created!')- expect(Spree::Brand.find_by(name: 'Puma')).to be_present- end-- it 'shows validation errors' do- visit spree.new_admin_brand_path-- click_on 'Create'- wait_for_turbo-- expect(page).to have_content("can't be blank")- end- end-- describe 'editing a brand' do- let!(:brand) { create(:brand, name: 'Nike') }-- it 'updates the brand successfully' do- visit spree.admin_brands_path- click_on 'Edit'-- fill_in 'Name', with: 'Nike Inc.'- within('#page-header') { click_button 'Update' }-- wait_for_turbo- expect(page).to have_content('Brand "Nike Inc." has been successfully updated!')- expect(brand.reload.name).to eq('Nike Inc.')- end- end-- describe 'deleting a brand' do- let!(:brand) { create(:brand, name: 'Nike') }-- it 'removes the brand' do- expect {- page.driver.submit :delete, spree.admin_brand_path(brand), {}- }.to change(Spree::Brand, :count).by(-1)- end- end-end-```--## Test Helpers--### Authorization Helper--Use `stub_authorization!` to bypass authorization checks in admin tests:--```ruby-RSpec.describe Spree::Admin::BrandsController, type: :controller do- stub_authorization! # Grants full admin access-- # ... your tests-end-```--### wait\_for\_turbo Helper--When testing with Turbo/Hotwire, use `wait_for_turbo` to ensure the page has fully loaded:--```ruby-click_on 'Create'-wait_for_turbo-expect(page).to have_content('Success!')-```--## Running Tests--### Prepare the test database--Tests run against a dedicated `spree_test` database, so your development data is never touched. Create it and load the schema once:--<CodeGroup>--```bash Spree CLI (Docker)-spree rails db:test:prepare-```--```bash Without Spree CLI-bin/rails db:test:prepare-```--</CodeGroup>--You rarely need to run this again — `rails_helper.rb` re-syncs the test schema automatically when you add migrations. It's the command to reach for when the test database gets into a broken or out-of-sync state.--### Run the suite--`spree rspec` runs `bundle exec rspec` inside the web container with `RAILS_ENV=test`. Everything after `rspec` is passed through, so file paths, line numbers, and flags work as usual:--<CodeGroup>--```bash Spree CLI (Docker)-spree rspec # all tests-spree rspec spec/models/spree/brand_spec.rb # specific file-spree rspec spec/models/spree/brand_spec.rb:15 # specific test-spree rspec --format documentation # documentation format-spree rspec spec/features/ # only feature tests-```--```bash Without Spree CLI-bundle exec rspec # all tests-bundle exec rspec spec/models/spree/brand_spec.rb # specific file-bundle exec rspec spec/models/spree/brand_spec.rb:15 # specific test-bundle exec rspec --format documentation # documentation format-bundle exec rspec spec/features/ # only feature tests-```--</CodeGroup>--<Accordion title="Troubleshooting: DatabaseCleaner refuses a remote database URL, or tests hit the development database">--Projects scaffolded before July 2026 set `DATABASE_URL` in `docker-compose.dev.yml`. A URL overrides `config/database.yml` for **every** Rails environment, so in-container tests pointed at the development database and tripped DatabaseCleaner's remote-URL safeguard. Two small changes bring an older project up to date:--1. In `docker-compose.dev.yml`, replace the `DATABASE_URL` entry under `environment:` with host/username parts, so each Rails environment resolves its own database from `database.yml`:--```yaml- DATABASE_HOST: postgres- DATABASE_USERNAME: postgres-```--2. In `spec/rails_helper.rb`, force the test environment — the dev container bakes in `RAILS_ENV=development`:--```ruby-ENV['RAILS_ENV'] = 'test'-```--Then restart the stack (`Ctrl+C` and `spree dev`) so the container picks up the new environment.--</Accordion>--## Best Practices--<CardGroup cols={2}>- <Card title="Use build over create" icon="bolt">- Use `build` instead of `create` when you don't need a persisted record. It's faster because it skips database operations.- </Card>-- <Card title="Use let over instance variables" icon="code">- Prefer `let` and `let!` over instance variables. They're lazily evaluated and scoped to each example.- </Card>-- <Card title="One assertion per test" icon="check">- Keep tests focused on a single behavior. Use `aggregate_failures` if you need multiple assertions.- </Card>-- <Card title="Test behavior, not implementation" icon="eye">- Focus on what the code does, not how it does it. This makes tests more resilient to refactoring.- </Card>-</CardGroup>--### Example: aggregate\_failures--```ruby-it 'creates brand with all attributes', :aggregate_failures do- brand = create(:brand, name: 'Nike')-- expect(brand.name).to eq('Nike')- expect(brand.slug).to eq('nike')-end-```--## Complete Test Suite Structure--After completing this tutorial, your test structure should look like:--```-spec/-├── factories/-│ └── spree/-│ └── brand_factory.rb-├── models/-│ └── spree/-│ ├── brand_spec.rb-│ └── product_decorator_spec.rb-├── controllers/-│ └── spree/-│ ├── admin/-│ │ └── brands_controller_spec.rb-│ └── api/-│ └── v3/-│ └── store/-│ ├── brands_controller_spec.rb-│ └── products_brand_spec.rb-├── features/-│ └── spree/-│ └── admin/-│ └── brands_spec.rb-├── support/-│ └── (various support files)-├── rails_helper.rb-└── spec_helper.rb-```--## Related Documentation--* [Model Tutorial](/developer/tutorial/model) - Creating the Brand model-* [Admin Tutorial](/developer/tutorial/admin) - Building the admin interface-* [Extending Core Models](/developer/tutorial/extending-models) - Connecting Brands to Products-* [API Tutorial](/developer/tutorial/api) - Creating Brand API endpoints-* [Spree CLI](/developer/cli/quickstart) - `spree rspec` and the other dev workflow commands-* [RSpec Documentation](https://rspec.info/documentation/) - Official RSpec docs-* [Factory Bot Documentation](https://github.com/thoughtbot/factory_bot/blob/main/GETTING_STARTED.md) - Factory Bot guide------+- Model and factory setup+- Request specs for the Admin and Store API endpoints+- Dashboard plugin tests with Vitest+- An end-to-end Playwright spec: create an FAQ in the dashboard, see it on the storefrontdiff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdxindex 431f37a65f..b8c50ea2a1 100644--- a/docs/developer/upgrades/5.6-to-6.0.mdx+++ b/docs/developer/upgrades/5.6-to-6.0.mdx@@ -5,7 +5,7 @@ hidden: true---<Info>- Before proceeding to upgrade, please ensure you're at [Spree 5.6](/developer/upgrades/5.5-to-5.6). Spree 6.0 requires **Rails 8.1** and is the designated breaking-change window for the platform — read the behavioral changes section even if your upgrade runs clean.+ Before proceeding to upgrade, please ensure you're at [Spree 5.6](/v5/developer/upgrades/5.5-to-5.6). Spree 6.0 requires **Rails 8.1** and is the designated breaking-change window for the platform — read the behavioral changes section even if your upgrade runs clean.</Info>Spree 6.0 is a major release. The headline changes:@@ -450,7 +450,7 @@ buckets, and only the last needs this hook:| What you were adding | Where it goes in 6.0 || --- | --- |-| A merchant-managed field (text, number, dropdown) | [Custom Fields](/developer/core-concepts/custom-fields) — no code, and filterable/sortable |+| A merchant-managed field (text, number, dropdown) | [Custom Fields](/developer/core-concepts/metafields) — no code, and filterable/sortable || Config for an STI type you register (promotion rule, delivery method rule, …) | `additional_permitted_attributes` on that subclass, as before — unchanged || A real database column your extension added to a core model | `additional_permitted_attributes` on the model |diff --git a/docs/docs.json b/docs/docs.jsonindex 081686a8c5..0ac1c86f2c 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -1,9 +1,11 @@{"$schema": "https://mintlify.com/docs.json","name": "Spree Commerce documentation",- "theme": "sequoia",+ "theme": "almond","colors": {- "primary": "#0177FF"+ "primary": "#0077ff",+ "light": "#4d9fff",+ "dark": "#0060ce"},"fonts": {"body": {@@ -22,7 +24,6 @@"favicon": "/favicon.png","seo": {"metatags": {- "canonical": "https://spreecommerce.org/docs","og:locale": "en_US","twitter:site": "@spreecommerce"}@@ -77,47 +78,47 @@},{"source": "/developer/tutorial/storefront",- "destination": "/developer/storefront/rails/storefront"+ "destination": "/v5/developer/storefront/rails/storefront"},{"source": "/developer/tutorial/page-builder",- "destination": "/developer/storefront/rails/sections"+ "destination": "/v5/developer/storefront/rails/sections"},{"source": "/developer/storefront/storefront",- "destination": "/developer/storefront/rails/storefront"+ "destination": "/v5/developer/storefront/rails/storefront"},{"source": "/developer/storefront/themes",- "destination": "/developer/storefront/rails/themes"+ "destination": "/v5/developer/storefront/rails/themes"},{"source": "/developer/storefront/sections",- "destination": "/developer/storefront/rails/sections"+ "destination": "/v5/developer/storefront/rails/sections"},{"source": "/developer/storefront/blocks",- "destination": "/developer/storefront/rails/blocks"+ "destination": "/v5/developer/storefront/rails/blocks"},{"source": "/developer/storefront/pages",- "destination": "/developer/storefront/rails/pages"+ "destination": "/v5/developer/storefront/rails/pages"},{"source": "/developer/storefront/links",- "destination": "/developer/storefront/rails/links"+ "destination": "/v5/developer/storefront/rails/links"},{"source": "/developer/storefront/helper-methods",- "destination": "/developer/storefront/rails/helper-methods"+ "destination": "/v5/developer/storefront/rails/helper-methods"},{"source": "/developer/storefront/custom-css",- "destination": "/developer/storefront/rails/custom-css"+ "destination": "/v5/developer/storefront/rails/custom-css"},{"source": "/developer/storefront/custom-javascript",- "destination": "/developer/storefront/rails/custom-javascript"+ "destination": "/v5/developer/storefront/rails/custom-javascript"},{"source": "/api-reference/introduction",@@ -129,11 +130,11 @@},{"source": "/developer/tutorial/file-uploads",- "destination": "/developer/tutorial/admin"+ "destination": "/v5/developer/tutorial/admin"},{"source": "/developer/tutorial/store-api",- "destination": "/developer/tutorial/api"+ "destination": "/v5/developer/tutorial/api"},{"source": "/developer/multi-store/quickstart",@@ -146,6 +147,270 @@{"source": "/developer/multi-tenant/installation","destination": "/developer/multi-tenant/quickstart"+ },+ {+ "source": "/developer/storefront/rails/blocks",+ "destination": "/v5/developer/storefront/rails/blocks"+ },+ {+ "source": "/developer/storefront/rails/custom-css",+ "destination": "/v5/developer/storefront/rails/custom-css"+ },+ {+ "source": "/developer/storefront/rails/custom-javascript",+ "destination": "/v5/developer/storefront/rails/custom-javascript"+ },+ {+ "source": "/developer/storefront/rails/helper-methods",+ "destination": "/v5/developer/storefront/rails/helper-methods"+ },+ {+ "source": "/developer/storefront/rails/links",+ "destination": "/v5/developer/storefront/rails/links"+ },+ {+ "source": "/developer/storefront/rails/pages",+ "destination": "/v5/developer/storefront/rails/pages"+ },+ {+ "source": "/developer/storefront/rails/sections",+ "destination": "/v5/developer/storefront/rails/sections"+ },+ {+ "source": "/developer/storefront/rails/storefront",+ "destination": "/v5/developer/storefront/rails/storefront"+ },+ {+ "source": "/developer/storefront/rails/themes",+ "destination": "/v5/developer/storefront/rails/themes"+ },+ {+ "source": "/developer/admin/admin",+ "destination": "/v5/developer/admin/admin"+ },+ {+ "source": "/developer/admin/authentication",+ "destination": "/v5/developer/admin/authentication"+ },+ {+ "source": "/developer/admin/components",+ "destination": "/v5/developer/admin/components"+ },+ {+ "source": "/developer/admin/custom-css",+ "destination": "/v5/developer/admin/custom-css"+ },+ {+ "source": "/developer/admin/custom-javascript",+ "destination": "/v5/developer/admin/custom-javascript"+ },+ {+ "source": "/developer/admin/extending-ui",+ "destination": "/v5/developer/admin/extending-ui"+ },+ {+ "source": "/developer/admin/form-builder",+ "destination": "/v5/developer/admin/form-builder"+ },+ {+ "source": "/developer/admin/helper-methods",+ "destination": "/v5/developer/admin/helper-methods"+ },+ {+ "source": "/developer/admin/navigation",+ "destination": "/v5/developer/admin/navigation"+ },+ {+ "source": "/developer/admin/tables",+ "destination": "/v5/developer/admin/tables"+ },+ {+ "source": "/developer/tutorial/admin",+ "destination": "/v5/developer/tutorial/admin"+ },+ {+ "source": "/developer/tutorial/api",+ "destination": "/v5/developer/tutorial/api"+ },+ {+ "source": "/developer/tutorial/sdk",+ "destination": "/v5/developer/tutorial/sdk"+ },+ {+ "source": "/developer/tutorial/extending-models",+ "destination": "/v5/developer/tutorial/extending-models"+ },+ {+ "source": "/developer/upgrades/2.0-to-2.1",+ "destination": "/v5/developer/upgrades/2.0-to-2.1"+ },+ {+ "source": "/developer/upgrades/2.1-to-2.2",+ "destination": "/v5/developer/upgrades/2.1-to-2.2"+ },+ {+ "source": "/developer/upgrades/2.2-to-2.3",+ "destination": "/v5/developer/upgrades/2.2-to-2.3"+ },+ {+ "source": "/developer/upgrades/2.3-to-2.4",+ "destination": "/v5/developer/upgrades/2.3-to-2.4"+ },+ {+ "source": "/developer/upgrades/3.0-to-3.1",+ "destination": "/v5/developer/upgrades/3.0-to-3.1"+ },+ {+ "source": "/developer/upgrades/3.1-to-3.2",+ "destination": "/v5/developer/upgrades/3.1-to-3.2"+ },+ {+ "source": "/developer/upgrades/3.2-to-3.3",+ "destination": "/v5/developer/upgrades/3.2-to-3.3"+ },+ {+ "source": "/developer/upgrades/3.3-to-3.4",+ "destination": "/v5/developer/upgrades/3.3-to-3.4"+ },+ {+ "source": "/developer/upgrades/3.4-to-3.5",+ "destination": "/v5/developer/upgrades/3.4-to-3.5"+ },+ {+ "source": "/developer/upgrades/3.5-to-3.6",+ "destination": "/v5/developer/upgrades/3.5-to-3.6"+ },+ {+ "source": "/developer/upgrades/3.6-to-3.7",+ "destination": "/v5/developer/upgrades/3.6-to-3.7"+ },+ {+ "source": "/developer/upgrades/3.7-to-4.0",+ "destination": "/v5/developer/upgrades/3.7-to-4.0"+ },+ {+ "source": "/developer/upgrades/4.0-to-4.1",+ "destination": "/v5/developer/upgrades/4.0-to-4.1"+ },+ {+ "source": "/developer/upgrades/4.1-to-4.2",+ "destination": "/v5/developer/upgrades/4.1-to-4.2"+ },+ {+ "source": "/developer/upgrades/4.2-to-4.3",+ "destination": "/v5/developer/upgrades/4.2-to-4.3"+ },+ {+ "source": "/developer/upgrades/4.3-to-4.4",+ "destination": "/v5/developer/upgrades/4.3-to-4.4"+ },+ {+ "source": "/developer/upgrades/4.4-to-4.5",+ "destination": "/v5/developer/upgrades/4.4-to-4.5"+ },+ {+ "source": "/developer/upgrades/4.5-to-4.6",+ "destination": "/v5/developer/upgrades/4.5-to-4.6"+ },+ {+ "source": "/developer/upgrades/4.6-to-4.7",+ "destination": "/v5/developer/upgrades/4.6-to-4.7"+ },+ {+ "source": "/developer/upgrades/4.x-to-4.8",+ "destination": "/v5/developer/upgrades/4.x-to-4.8"+ },+ {+ "source": "/developer/upgrades/4.8-to-4.9",+ "destination": "/v5/developer/upgrades/4.8-to-4.9"+ },+ {+ "source": "/developer/upgrades/4.9-to-4.10",+ "destination": "/v5/developer/upgrades/4.9-to-4.10"+ },+ {+ "source": "/developer/upgrades/4.10-to-5.0",+ "destination": "/v5/developer/upgrades/4.10-to-5.0"+ },+ {+ "source": "/developer/upgrades/5.0-to-5.1",+ "destination": "/v5/developer/upgrades/5.0-to-5.1"+ },+ {+ "source": "/developer/upgrades/5.1-to-5.2",+ "destination": "/v5/developer/upgrades/5.1-to-5.2"+ },+ {+ "source": "/developer/upgrades/5.2-to-5.3",+ "destination": "/v5/developer/upgrades/5.2-to-5.3"+ },+ {+ "source": "/developer/upgrades/5.3-to-5.4",+ "destination": "/v5/developer/upgrades/5.3-to-5.4"+ },+ {+ "source": "/developer/upgrades/5.4-to-5.5",+ "destination": "/v5/developer/upgrades/5.4-to-5.5"+ },+ {+ "source": "/developer/upgrades/5.5-to-5.6",+ "destination": "/v5/developer/upgrades/5.5-to-5.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"+ },+ {+ "source": "/developer/customization/emails",+ "destination": "/v5/developer/customization/emails"+ },+ {+ "source": "/developer/core-concepts/adjustments",+ "destination": "/developer/core-concepts/taxes-discounts-fees"+ },+ {+ "source": "/developer/core-concepts/shipments",+ "destination": "/developer/core-concepts/fulfillments"+ },+ {+ "source": "/developer/core-concepts/reports",+ "destination": "/v5/developer/core-concepts/reports"+ },+ {+ "source": "/developer/multi-vendor/quickstart",+ "destination": "/developer/how-to/build-a-marketplace"+ },+ {+ "source": "/developer/multi-vendor/installation",+ "destination": "/developer/how-to/build-a-marketplace"+ },+ {+ "source": "/developer/advanced/adding_spree_to_rails_app",+ "destination": "/v5/developer/advanced/adding_spree_to_rails_app"+ },+ {+ "source": "/user/settings/checkout",+ "destination": "/v5/user/settings/checkout"+ },+ {+ "source": "/user/manage-products/product-properties",+ "destination": "/v5/user/manage-products/product-properties"+ },+ {+ "source": "/developer/deployment/telemetry",+ "destination": "/developer/providers/observability"+ },+ {+ "source": "/developer/multi-vendor",+ "destination": "/developer/how-to/build-a-marketplace"}],"contextual": {@@ -162,251 +427,312 @@"navigation": {"versions": [{- "version": "v5.x",+ "version": "v6.x","default": true,"tabs": [{- "tab": "Guides",- "menu": [+ "tab": "Documentation",+ "groups": [{- "item": "Getting Started",- "icon": "rocket",- "description": "Quickstart guide and core concepts",- "groups": [- {- "group": "Getting started",- "icon": "rocket",- "pages": [- "developer/getting-started/quickstart"- ]- },+ "group": "Develop",+ "pages": [{- "group": "Platform",- "icon": "settings",+ "group": "Getting Started","pages": [- "developer/core-concepts/architecture",- "developer/core-concepts/stores",- "developer/core-concepts/channels",- "developer/core-concepts/markets",- "developer/core-concepts/customers",- "developer/core-concepts/staff-roles"- ]+ "developer/getting-started/quickstart",+ "developer/create-spree-app/quickstart",+ "developer/core-concepts/architecture"+ ],+ "icon": "rocket"},{- "group": "Catalog",- "icon": "package",+ "group": "Tutorial","pages": [- "developer/core-concepts/products",- "developer/core-concepts/pricing",- "developer/core-concepts/inventory",- "developer/core-concepts/media",- "developer/core-concepts/search-filtering"- ]+ "developer/tutorial/introduction",+ "developer/tutorial/model",+ "developer/tutorial/admin-api",+ "developer/tutorial/dashboard-plugin",+ "developer/tutorial/store-api",+ "developer/tutorial/storefront",+ "developer/tutorial/events",+ "developer/tutorial/testing"+ ],+ "icon": "graduation-cap"},{- "group": "Cart & Checkout",- "icon": "shopping-cart",+ "group": "AI-Assisted Development","pages": [- "developer/core-concepts/orders",- "developer/core-concepts/payments",- "developer/core-concepts/taxes",- "developer/core-concepts/promotions",- "developer/core-concepts/store-credits-gift-cards"- ]+ "developer/agentic/overview",+ "developer/agentic/agent-skills",+ "developer/agentic/mcp",+ "developer/agentic/llm-docs",+ "developer/cli/admin-api"+ ],+ "icon": "sparkles"},{- "group": "Fulfillment",- "icon": "truck",+ "group": "Core Concepts","pages": [- "developer/core-concepts/shipments",- "developer/core-concepts/addresses",- "developer/core-concepts/adjustments",- "developer/core-concepts/calculators"- ]+ {+ "group": "Platform",+ "pages": [+ "developer/core-concepts/stores",+ "developer/core-concepts/channels",+ "developer/core-concepts/markets",+ "developer/core-concepts/customers",+ "developer/core-concepts/staff-roles"+ ]+ },+ {+ "group": "Catalog",+ "pages": [+ "developer/core-concepts/products",+ "developer/core-concepts/pricing",+ "developer/core-concepts/inventory",+ "developer/core-concepts/media",+ "developer/core-concepts/search-filtering"+ ]+ },+ {+ "group": "Cart & Checkout",+ "pages": [+ "developer/core-concepts/carts",+ "developer/core-concepts/orders",+ "developer/core-concepts/payments",+ "developer/core-concepts/taxes",+ "developer/core-concepts/taxes-discounts-fees",+ "developer/core-concepts/promotions",+ "developer/core-concepts/store-credits-gift-cards"+ ]+ },+ {+ "group": "Fulfillment",+ "pages": [+ "developer/core-concepts/fulfillments",+ "developer/core-concepts/returns-exchanges-claims",+ "developer/core-concepts/addresses",+ "developer/core-concepts/calculators"+ ]+ },+ {+ "group": "Extensibility",+ "pages": [+ "developer/core-concepts/events",+ "developer/core-concepts/webhooks",+ "developer/core-concepts/translations",+ "developer/core-concepts/slugs",+ "developer/core-concepts/metafields",+ "developer/core-concepts/imports-exports"+ ]+ }+ ],+ "icon": "book-open"},{- "group": "Extensibility",- "icon": "plug",- "pages": [- "developer/core-concepts/events",- "developer/core-concepts/webhooks",- "developer/core-concepts/translations",- "developer/core-concepts/slugs",- "developer/core-concepts/metafields",- "developer/core-concepts/reports",- "developer/core-concepts/imports-exports"- ]- }- ]- },- {- "item": "Building a Storefront",- "icon": "store",- "description": "Next.js, custom frontend, or Rails engine",- "groups": [- {- "group": "Next.js Storefront",- "pages": [- "developer/storefront/nextjs/quickstart",- "developer/storefront/nextjs/architecture",- "developer/storefront/nextjs/multi-region",- "developer/storefront/nextjs/customization",- "developer/storefront/nextjs/emails",- "developer/storefront/nextjs/wholesale",- "developer/storefront/nextjs/wallet-payments",- "developer/storefront/nextjs/testing",- "developer/storefront/nextjs/environment-variables",- "developer/storefront/nextjs/deployment"- ]- }- ]- },- {- "item": "Use Cases",- "icon": "book-open",- "description": "Multi-store/multi-tenant, and marketplace setups",- "groups": [- {- "group": "Multi-Tenant / Multi-Store",+ "group": "Providers & Integrations","pages": [- "developer/multi-tenant/quickstart",- "developer/multi-tenant/core-concepts",- "developer/multi-tenant/configuration"- ]+ "developer/providers/overview",+ "integrations/integrations",+ {+ "group": "Connect Your Systems",+ "pages": [+ "developer/providers/erp",+ "developer/providers/pim",+ "developer/providers/dam"+ ]+ },+ {+ "group": "Shipping & WMS",+ "pages": [+ "developer/providers/fulfillment",+ "developer/how-to/custom-delivery-rate-provider"+ ]+ },+ {+ "group": "Payments",+ "pages": [+ "developer/how-to/custom-payment-method",+ "integrations/payments/stripe",+ "integrations/payments/adyen",+ "integrations/payments/paypal",+ "integrations/payments/razorpay"+ ]+ },+ {+ "group": "Tax",+ "pages": [+ "integrations/tax/avalara"+ ]+ },+ {+ "group": "Search",+ "pages": [+ "developer/how-to/custom-search-provider",+ "integrations/search/meilisearch"+ ]+ },+ {+ "group": "Identity & SSO",+ "pages": [+ "developer/providers/sso",+ "developer/how-to/custom-api-authentication"+ ]+ },+ {+ "group": "Observability",+ "pages": [+ "developer/providers/observability"+ ]+ },+ {+ "group": "Marketing & Analytics",+ "pages": [+ "integrations/analytics/google-analytics",+ "integrations/analytics/google-tag-manager",+ "integrations/marketing/klaviyo"+ ]+ }+ ],+ "icon": "plug"},{- "group": "Multi-Vendor Marketplace",+ "group": "Admin Dashboard","pages": [- "developer/multi-vendor/quickstart",- "developer/multi-vendor/installation"- ]- }- ]- }- ]- },- {- "tab": "Framework",- "menu": [- {- "item": "Extending",- "icon": "puzzle",- "description": "Customize admin panel, API, and business logic",- "groups": [- {- "group": "Tutorial",- "icon": "graduation-cap",- "pages": [- "developer/tutorial/introduction",- "developer/tutorial/model",- "developer/tutorial/admin",- "developer/tutorial/extending-models",- "developer/tutorial/api",- "developer/tutorial/events",- "developer/tutorial/sdk",- "developer/tutorial/testing"- ]+ "developer/dashboard/overview",+ "developer/dashboard/concepts",+ {+ "group": "Customization",+ "pages": [+ "developer/dashboard/customization/quickstart",+ "developer/dashboard/customization/navigation",+ "developer/dashboard/customization/routes",+ "developer/dashboard/customization/slots",+ "developer/dashboard/customization/tables",+ "developer/dashboard/customization/translations",+ "developer/dashboard/customization/permissions",+ "developer/dashboard/customization/backend"+ ]+ },+ {+ "group": "Recipes",+ "pages": [+ "developer/dashboard/recipes/attribute-end-to-end",+ "developer/dashboard/recipes/custom-form-field",+ "developer/dashboard/recipes/page-action-button",+ "developer/dashboard/recipes/sidebar-widget"+ ]+ },+ {+ "group": "Plugins",+ "pages": [+ "developer/dashboard/plugins/overview",+ "developer/dashboard/plugins/scaffolding",+ "developer/dashboard/plugins/publishing",+ "developer/dashboard/plugins/distributing"+ ]+ },+ {+ "group": "Admin SDK",+ "pages": [+ "developer/sdk/admin/quickstart",+ "developer/sdk/admin/authentication",+ "developer/sdk/admin/resources",+ "developer/sdk/admin/querying-and-errors",+ "developer/sdk/admin/extending"+ ]+ },+ {+ "group": "Reference",+ "pages": [+ "developer/dashboard/public-api",+ "developer/dashboard/slots-catalog",+ "developer/dashboard/deployment"+ ]+ }+ ],+ "icon": "layout-dashboard"},{- "group": "Admin Panel",- "icon": "gauge",+ "group": "Building a Storefront","pages": [- "developer/admin/admin",- "developer/admin/extending-ui",- "developer/admin/navigation",- "developer/admin/tables",- "developer/admin/form-builder",- "developer/admin/components",- "developer/admin/helper-methods",- "developer/admin/authentication",- "developer/admin/custom-javascript",- "developer/admin/custom-css"- ]+ {+ "group": "Store SDK",+ "pages": [+ "developer/sdk/quickstart",+ "developer/sdk/authentication",+ "developer/sdk/configuration",+ "developer/sdk/extending"+ ]+ },+ {+ "group": "Working with the Store API",+ "pages": [+ "developer/sdk/store/products",+ "developer/sdk/store/cart-checkout",+ "developer/sdk/store/payments",+ "developer/sdk/store/markets",+ "developer/sdk/store/account",+ "developer/sdk/store/wishlists"+ ]+ },+ {+ "group": "Next.js Starter",+ "pages": [+ "developer/storefront/nextjs/quickstart",+ "developer/storefront/nextjs/architecture",+ "developer/storefront/nextjs/multi-region",+ "developer/storefront/nextjs/customization",+ "developer/storefront/nextjs/emails",+ "developer/storefront/nextjs/wholesale",+ "developer/storefront/nextjs/wallet-payments",+ "developer/storefront/nextjs/testing",+ "developer/storefront/nextjs/environment-variables",+ "developer/storefront/nextjs/deployment"+ ]+ }+ ],+ "icon": "store"},{- "group": "Customization Reference",- "icon": "wrench",+ "group": "Extending the Backend","pages": ["developer/customization/quickstart","developer/customization/configuration",- "developer/customization/authentication",- "developer/customization/checkout",- "developer/customization/permissions","developer/customization/workflows",+ "developer/customization/validations","developer/customization/dependencies",- "developer/customization/decorators","developer/customization/model-preferences","developer/customization/metadata",- "developer/customization/routes",- "developer/customization/api"- ]- }- ]- },- {- "item": "How-to Guides",- "icon": "book-open",- "description": "Step-by-step guides for common tasks",- "groups": [- {- "group": "Order Routing",- "icon": "route",- "pages": [- "developer/how-to/custom-order-routing"- ]+ "developer/customization/permissions",+ "developer/customization/api",+ "developer/customization/decorators"+ ],+ "icon": "code"},{- "group": "Stock Splitters",- "icon": "boxes-stacked",+ "group": "Guides","pages": [+ "developer/how-to/build-a-marketplace",+ "developer/how-to/build-a-b2b-store",+ "developer/how-to/sell-digital-products",+ {+ "group": "Multi-Tenant Platform",+ "pages": [+ "developer/multi-tenant/quickstart",+ "developer/multi-tenant/core-concepts",+ "developer/multi-tenant/configuration"+ ]+ },+ "developer/how-to/custom-promotion",+ "developer/how-to/custom-report",+ "developer/how-to/custom-document-numbers",+ "developer/how-to/custom-order-routing","developer/how-to/custom-stock-splitter"- ]- },- {- "group": "Payments",- "icon": "credit-card",- "pages": [- "developer/how-to/custom-payment-method"- ]- },- {- "group": "Promotions",- "icon": "tag",- "pages": [- "developer/how-to/custom-promotion"- ]- },- {- "group": "Reports",- "icon": "chart-bar",- "pages": [- "developer/how-to/custom-report"- ]- },- {- "group": "Search",- "icon": "search",- "pages": [- "developer/how-to/custom-search-provider"- ]+ ],+ "icon": "compass"},- {- "group": "Authentication",- "icon": "key",- "pages": [- "developer/how-to/custom-api-authentication"- ]- }- ]- },- {- "item": "Operations",- "icon": "server",- "description": "Deploy, upgrade, and maintain your store",- "groups": [{"group": "Deployment",- "icon": "server","pages": ["developer/deployment/quickstart","developer/deployment/docker",@@ -425,157 +751,37 @@"developer/deployment/background_jobs","developer/deployment/caching","developer/deployment/database"- ]+ ],+ "icon": "server"},{- "group": "Upgrading",- "icon": "circle-arrow-up",+ "group": "Operations","pages": [- "developer/upgrades/quickstart",+ "developer/cli/quickstart",{- "group": "Upgrade Guides",+ "group": "Upgrading","pages": [- "developer/upgrades/5.5-to-5.6",- "developer/upgrades/5.4-to-5.5",- "developer/upgrades/5.3-to-5.4",- "developer/upgrades/5.2-to-5.3",- "developer/upgrades/5.1-to-5.2",- "developer/upgrades/5.0-to-5.1",- "developer/upgrades/4.10-to-5.0",- "developer/upgrades/4.9-to-4.10",- "developer/upgrades/4.8-to-4.9",- "developer/upgrades/4.x-to-4.8",- "developer/upgrades/4.6-to-4.7",- "developer/upgrades/4.5-to-4.6",- "developer/upgrades/4.4-to-4.5",- "developer/upgrades/4.3-to-4.4",- "developer/upgrades/4.2-to-4.3",- "developer/upgrades/4.1-to-4.2",- "developer/upgrades/4.0-to-4.1",- "developer/upgrades/3.7-to-4.0",- "developer/upgrades/3.6-to-3.7",- "developer/upgrades/3.5-to-3.6",- "developer/upgrades/3.4-to-3.5",- "developer/upgrades/3.3-to-3.4",- "developer/upgrades/3.2-to-3.3",- "developer/upgrades/3.1-to-3.2",- "developer/upgrades/3.0-to-3.1",- "developer/upgrades/2.3-to-2.4",- "developer/upgrades/2.2-to-2.3",- "developer/upgrades/2.1-to-2.2",- "developer/upgrades/2.0-to-2.1"+ "developer/upgrades/quickstart",+ "developer/upgrades/5.6-to-6.0"+ ]+ },+ {+ "group": "Contributing",+ "pages": [+ "developer/contributing/quickstart",+ "developer/contributing/developing-spree",+ "developer/contributing/creating-an-extension"+ ]+ },+ {+ "group": "Security",+ "pages": [+ "developer/security/security_policy",+ "developer/security/pci_compliance"]}- ]- },- {- "group": "Contributing",- "icon": "heart",- "pages": [- "developer/contributing/quickstart",- "developer/contributing/developing-spree",- "developer/contributing/creating-an-extension"- ]- },- {- "group": "Security",- "icon": "shield",- "pages": [- "developer/security/security_policy",- "developer/security/pci_compliance"- ]- }- ]- }- ]- },- {- "tab": "SDK & Tools",- "menu": [- {- "item": "Store SDK",- "icon": "code",- "description": "TypeScript SDK for the Store API",- "groups": [- {- "group": "Getting Started",- "pages": [- "developer/sdk/quickstart",- "developer/sdk/authentication",- "developer/sdk/configuration",- "developer/sdk/extending"- ]- },- {- "group": "Store API",- "pages": [- "developer/sdk/store/products",- "developer/sdk/store/cart-checkout",- "developer/sdk/store/payments",- "developer/sdk/store/markets",- "developer/sdk/store/account",- "developer/sdk/store/wishlists"- ]- }- ]- },- {- "item": "Admin SDK",- "icon": "shield-check",- "description": "TypeScript SDK for the Admin API",- "groups": [- {- "group": "Admin SDK",- "pages": [- "developer/sdk/admin/quickstart",- "developer/sdk/admin/authentication",- "developer/sdk/admin/resources",- "developer/sdk/admin/querying-and-errors",- "developer/sdk/admin/extending"- ]- }- ]- },- {- "item": "CLI",- "icon": "square-terminal",- "description": "Command-line interface for Spree",- "groups": [- {- "group": "CLI",- "pages": [- "developer/cli/quickstart",- "developer/cli/admin-api"- ]- }- ]- },- {- "item": "create-spree-app",- "icon": "rocket",- "description": "Scaffold a new Spree project",- "groups": [- {- "group": "create-spree-app",- "pages": [- "developer/create-spree-app/quickstart"- ]- }- ]- },- {- "item": "Agentic Development",- "icon": "bot",- "description": "Build Spree with AI coding agents",- "groups": [- {- "group": "Agentic Development",- "pages": [- "developer/agentic/overview",- "developer/agentic/agent-skills",- "developer/agentic/mcp",- "developer/agentic/llm-docs"- ]+ ],+ "icon": "settings"}]}@@ -584,355 +790,232 @@{"tab": "API Reference","menu": [- {- "item": "Store API",- "icon": "store",- "description": "REST API for storefronts and custom integrations",- "groups": [- {- "group": "API basics",- "pages": [- "api-reference/store-api/introduction",- "api-reference/store-api/authentication",- "api-reference/store-api/errors",- "api-reference/store-api/idempotency",- "api-reference/store-api/rate-limitting",- "api-reference/store-api/querying",- "api-reference/store-api/relations",- "api-reference/store-api/metadata",- "api-reference/store-api/localization",- "api-reference/store-api/monetary-amounts",- "api-reference/store-api/migrating-from-storefront-api-v2"- ]- },- {- "group": "Endpoints",- "openapi": {- "source": "api-reference/store.yaml",- "directory": "api-reference/store-api"- }- }- ]- },- {- "item": "Admin API",- "icon": "shield",- "description": "REST API for pragmatically managing stores",- "groups": [- {- "group": "API basics",- "pages": [- "api-reference/admin-api/introduction",- "api-reference/admin-api/authentication",- "api-reference/admin-api/errors",- "api-reference/admin-api/querying",- "api-reference/admin-api/monetary-amounts",- "api-reference/admin-api/endpoints"- ]- },- {- "group": "Endpoints",- "openapi": {- "source": "api-reference/admin.yaml",- "directory": "api-reference/admin-api"- }- }- ]- },- {- "item": "Webhooks",- "icon": "webhook",- "description": "Event payloads and delivery reference",- "groups": [- {- "group": "Webhooks",- "pages": [- "api-reference/webhooks-events"- ]- }- ]- },- {- "item": "Legacy API v2",- "icon": "clock",- "description": "Previous-generation Storefront and Platform APIs",- "groups": [- {- "group": "API basics",- "pages": [- "api-reference/v2/introduction",- "api-reference/v2/pagination",- "api-reference/v2/filtering-and-sorting",- "api-reference/v2/fetching-multiple-resources"- ]- },- {- "group": "Tutorials",- "pages": [- "api-reference/tutorials/quick-checkout-with-stripe",- "api-reference/tutorials/adyen-integration-guide-for-android",- "api-reference/tutorials/adyen-integration-guide-for-ios"- ]- },- {- "group": "Storefront API",- "pages": [- "api-reference/storefront/authentication"- ],- "openapi": {- "source": "api-reference/storefront.yaml",- "directory": "api-reference/storefront"- }- },- {- "group": "Platform API",- "pages": [- "api-reference/platform/authentication"- ],- "openapi": {- "source": "api-reference/platform.yaml",- "directory": "api-reference/platform"- }- }- ]- }- ]- },- {- "tab": "Integrations",- "groups": [- {- "group": "Integrations",- "pages": [- "integrations/integrations"- ]- },- {- "group": "Payments",- "pages": [- "integrations/payments/stripe",- "integrations/payments/adyen",- "integrations/payments/paypal",- "integrations/payments/razorpay"- ]- },- {- "group": "Tax",- "pages": [- "integrations/tax/avalara"- ]- },- {- "group": "Search",- "pages": [- "integrations/search/meilisearch"- ]- },- {- "group": "Analytics",- "pages": [- "integrations/analytics/google-analytics",- "integrations/analytics/google-tag-manager"- ]- },- {- "group": "Marketing",- "pages": [- "integrations/marketing/klaviyo"- ]- }- ]- },- {- "tab": "User Guide",- "groups": [- {- "group": "Introduction",- "pages": [- "user/what-is-spree-commerce",- "user/using-spree",- "user/user-quickstart-guide"- ]- },- {- "group": "Migration",- "pages": [- "user/migration/migrate-from-shopify"- ]- },- {- "group": "How-to Guides",- "pages": [- "user/how-to/multi-currency-pricing",- "user/how-to/multiple-languages",- "user/how-to/multi-region-pricing",- "user/how-to/wholesale-pricing",- "user/how-to/volume-pricing",- "user/how-to/regional-wholesale",- "user/how-to/regional-volume",- "user/how-to/schedule-sale-pricing"- ]- },- {- "group": "Products",- "pages": [+ {+ "item": "Store API",+ "icon": "store",+ "description": "REST API for storefronts and custom integrations",+ "groups": [{- "group": "Create & Edit Products",+ "group": "API basics","pages": [- "user/products/creating-products",- "user/products/deleting-products",- "user/products/editing-products",- "user/products/editing-multi-variant-products",- "user/products/cloning-products"+ "api-reference/store-api/introduction",+ "api-reference/store-api/authentication",+ "api-reference/store-api/errors",+ "api-reference/store-api/idempotency",+ "api-reference/store-api/rate-limitting",+ "api-reference/store-api/querying",+ "api-reference/store-api/relations",+ "api-reference/store-api/metadata",+ "api-reference/store-api/localization",+ "api-reference/store-api/monetary-amounts",+ "api-reference/store-api/migrating-from-storefront-api-v2"]},{- "group": "Manage Products",- "pages": [- "user/manage-products/search-products",- "user/manage-products/bulk-product-operations",- "user/manage-products/price-lists",- "user/manage-products/export-products",- "user/manage-products/import-products",- "user/manage-products/multi-currency-import-export",- "user/manage-products/product-import-file-template",- "user/manage-products/translations",- "user/manage-products/stock-levels",- "user/manage-products/stock-transfers",- "user/manage-products/product-taxonomies",- "user/manage-products/product-options",- "user/manage-products/product-metafields"- ]+ "group": "Endpoints",+ "openapi": {+ "source": "api-reference/store.yaml",+ "directory": "api-reference/store-api"+ }}]},{- "group": "Orders",- "pages": [- "user/orders/order-states",- "user/orders/processing-orders",- "user/orders/creating-orders",- "user/orders/editing-orders",- "user/orders/order-adjustments",- "user/orders/exporting-orders",- "user/orders/cancelling-orders",- "user/orders/refunding-orders",- "user/orders/searching-orders"- ]- },- {- "group": "Returns",- "pages": [- "user/settings/returns-configuration",- "user/returns/returns-processing"- ]- },- {- "group": "Customers",- "pages": [- "user/customers/create-customer",- "user/customers/customer-profile",- "user/customers/edit-customer",- "user/customers/issue-gift-card",- "user/customers/assign-store-credits",- "user/customers/searching-customers",- "user/customers/exporting-customers",- "user/customers/customer-groups"- ]- },- {- "group": "Promotions",- "pages": [- "user/promotions/create-a-promotion",- "user/promotions/promotion-rules",- "user/promotions/promotion-actions",- "user/promotions/gift-cards"- ]- },- {- "group": "Vendors",- "pages": [- "user/settings/marketplace",- "user/vendors/vendor-onboarding-shopify",- "user/vendors/vendor-onboarding-woocommerce",- "user/vendors/vendor-onboarding-manual",- "user/vendors/vendor-management",- "user/vendors/commission-rates",- "user/vendors/vendor-payouts",- "user/vendors/multi-vendor-checkout"- ]- },- {- "group": "Settings",- "pages": [- "user/settings/store-details",- "user/settings/sales-channels",- "user/settings/users",- "user/settings/emails",- "user/settings/policies",- "user/settings/payments",- "user/settings/markets",- "user/settings/zones",- "user/settings/shipping-methods",- "user/settings/tax",- "user/settings/locations",- "user/settings/metafields"+ "item": "Admin API",+ "icon": "shield",+ "description": "REST API for pragmatically managing stores",+ "groups": [+ {+ "group": "API basics",+ "pages": [+ "api-reference/admin-api/introduction",+ "api-reference/admin-api/authentication",+ "api-reference/admin-api/errors",+ "api-reference/admin-api/querying",+ "api-reference/admin-api/monetary-amounts",+ "api-reference/admin-api/endpoints"+ ]+ },+ {+ "group": "Endpoints",+ "openapi": {+ "source": "api-reference/admin.yaml",+ "directory": "api-reference/admin-api"+ }+ }]},{- "group": "Security",- "pages": [- "user/security"+ "item": "Webhooks",+ "icon": "webhook",+ "description": "Event payloads and delivery reference",+ "groups": [+ {+ "group": "Webhooks",+ "pages": [+ "api-reference/webhooks-events"+ ]+ }]}]},{- "tab": "Solutions",+ "tab": "User Guide","groups": [{- "group": "Overview",- "pages": [- "use-case/overview"- ]- },- {- "group": "B2B Commerce",- "pages": [- "use-case/b2b/b2b-commerce-model",- "use-case/b2b/b2b-capabilities",- "use-case/b2b/b2b-admin-capabilities",- "use-case/b2b/b2b-buyer-capabilities"- ]- },- {- "group": "Digital Products",- "pages": [- "use-case/digital-products/model",- "use-case/digital-products/capabilities",- "use-case/digital-products/admin-capabilities"- ]- },- {- "group": "Multi-Tenant Platform",- "pages": [- "use-case/multi-tenant/multi-tenant-model",- "use-case/multi-tenant/multi-tenant-capabilities",- "use-case/multi-tenant/super-admin-capabilities",- "use-case/multi-tenant/tenant-capabilities",- "use-case/multi-tenant/franchises-and-reseller-networks",- "use-case/multi-tenant/multi-brand-enterprise-model",- "use-case/multi-tenant/white-label-saas"- ]- },- {- "group": "Multi-Vendor Marketplace",+ "group": "Manage","pages": [- "use-case/marketplace/model",- "use-case/marketplace/capabilities",- "use-case/marketplace/admin-dashboard",- "use-case/marketplace/vendor-dashboard",- "use-case/marketplace/customer-ux"+ {+ "group": "Introduction",+ "icon": "book-open",+ "pages": [+ "user/what-is-spree-commerce",+ "user/using-spree",+ "user/user-quickstart-guide"+ ]+ },+ {+ "group": "Migration",+ "pages": [+ "user/migration/migrate-from-shopify"+ ],+ "icon": "arrow-right-left"+ },+ {+ "group": "How-to Guides",+ "pages": [+ "user/how-to/multi-currency-pricing",+ "user/how-to/multiple-languages",+ "user/how-to/multi-region-pricing",+ "user/how-to/wholesale-pricing",+ "user/how-to/volume-pricing",+ "user/how-to/regional-wholesale",+ "user/how-to/regional-volume",+ "user/how-to/schedule-sale-pricing"+ ],+ "icon": "compass"+ },+ {+ "group": "Products",+ "pages": [+ {+ "group": "Create & Edit Products",+ "pages": [+ "user/products/creating-products",+ "user/products/deleting-products",+ "user/products/editing-products",+ "user/products/editing-multi-variant-products",+ "user/products/cloning-products"+ ]+ },+ {+ "group": "Manage Products",+ "pages": [+ "user/manage-products/search-products",+ "user/manage-products/bulk-product-operations",+ "user/manage-products/price-lists",+ "user/manage-products/export-products",+ "user/manage-products/import-products",+ "user/manage-products/multi-currency-import-export",+ "user/manage-products/product-import-file-template",+ "user/manage-products/translations",+ "user/manage-products/stock-levels",+ "user/manage-products/stock-transfers",+ "user/manage-products/product-taxonomies",+ "user/manage-products/product-options",+ "user/manage-products/product-metafields"+ ]+ }+ ],+ "icon": "package"+ },+ {+ "group": "Orders",+ "pages": [+ "user/orders/order-states",+ "user/orders/processing-orders",+ "user/orders/creating-orders",+ "user/orders/editing-orders",+ "user/orders/order-adjustments",+ "user/orders/exporting-orders",+ "user/orders/cancelling-orders",+ "user/orders/refunding-orders",+ "user/orders/searching-orders"+ ],+ "icon": "shopping-cart"+ },+ {+ "group": "Returns",+ "pages": [+ "user/settings/returns-configuration",+ "user/returns/returns-processing"+ ],+ "icon": "undo-2"+ },+ {+ "group": "Customers",+ "pages": [+ "user/customers/create-customer",+ "user/customers/customer-profile",+ "user/customers/edit-customer",+ "user/customers/issue-gift-card",+ "user/customers/assign-store-credits",+ "user/customers/searching-customers",+ "user/customers/exporting-customers",+ "user/customers/customer-groups"+ ],+ "icon": "users"+ },+ {+ "group": "Promotions",+ "pages": [+ "user/promotions/create-a-promotion",+ "user/promotions/promotion-rules",+ "user/promotions/promotion-actions",+ "user/promotions/gift-cards"+ ],+ "icon": "ticket-percent"+ },+ {+ "group": "Vendors",+ "pages": [+ "user/settings/marketplace",+ "user/vendors/vendor-onboarding-shopify",+ "user/vendors/vendor-onboarding-woocommerce",+ "user/vendors/vendor-onboarding-manual",+ "user/vendors/vendor-management",+ "user/vendors/commission-rates",+ "user/vendors/vendor-payouts",+ "user/vendors/multi-vendor-checkout"+ ],+ "icon": "store"+ },+ {+ "group": "Settings",+ "pages": [+ "user/settings/store-details",+ "user/settings/sales-channels",+ "user/settings/users",+ "user/settings/emails",+ "user/settings/policies",+ "user/settings/payments",+ "user/settings/markets",+ "user/settings/zones",+ "user/settings/shipping-methods",+ "user/settings/tax",+ "user/settings/locations",+ "user/settings/metafields"+ ],+ "icon": "settings"+ },+ {+ "group": "Security",+ "pages": [+ "user/security"+ ],+ "icon": "shield"+ }]}]@@ -940,8 +1023,7 @@]},{- "version": "v6.x",- "tag": "beta",+ "version": "v5.x","tabs": [{"tab": "Guides",@@ -955,65 +1037,64 @@"group": "Getting started","icon": "rocket","pages": [- "developer/getting-started/quickstart"+ "v5/developer/getting-started/quickstart"]},{"group": "Platform","icon": "settings","pages": [- "developer/core-concepts/architecture",- "developer/core-concepts/stores",- "developer/core-concepts/channels",- "developer/core-concepts/markets",- "developer/core-concepts/customers",- "developer/core-concepts/staff-roles"+ "v5/developer/core-concepts/architecture",+ "v5/developer/core-concepts/stores",+ "v5/developer/core-concepts/channels",+ "v5/developer/core-concepts/markets",+ "v5/developer/core-concepts/customers",+ "v5/developer/core-concepts/staff-roles"]},{"group": "Catalog","icon": "package","pages": [- "developer/core-concepts/products",- "developer/core-concepts/pricing",- "developer/core-concepts/inventory",- "developer/core-concepts/media",- "developer/core-concepts/search-filtering"+ "v5/developer/core-concepts/products",+ "v5/developer/core-concepts/pricing",+ "v5/developer/core-concepts/inventory",+ "v5/developer/core-concepts/media",+ "v5/developer/core-concepts/search-filtering"]},{"group": "Cart & Checkout","icon": "shopping-cart","pages": [- "v6/developer/core-concepts/carts",- "v6/developer/core-concepts/orders",- "developer/core-concepts/payments",- "developer/core-concepts/taxes",- "v6/developer/core-concepts/taxes-discounts-fees",- "v6/developer/core-concepts/promotions",- "v6/developer/core-concepts/store-credits-gift-cards"+ "v5/developer/core-concepts/orders",+ "v5/developer/core-concepts/payments",+ "v5/developer/core-concepts/taxes",+ "v5/developer/core-concepts/promotions",+ "v5/developer/core-concepts/store-credits-gift-cards"]},{"group": "Fulfillment","icon": "truck","pages": [- "v6/developer/core-concepts/fulfillments",- "v6/developer/core-concepts/returns-exchanges-claims",- "developer/core-concepts/addresses",- "developer/core-concepts/calculators"+ "v5/developer/core-concepts/shipments",+ "v5/developer/core-concepts/addresses",+ "v5/developer/core-concepts/adjustments",+ "v5/developer/core-concepts/calculators"]},{"group": "Extensibility","icon": "plug","pages": [- "developer/core-concepts/events",- "developer/core-concepts/webhooks",- "developer/core-concepts/translations",- "developer/core-concepts/slugs",- "developer/core-concepts/metafields",- "v6/developer/core-concepts/imports-exports"+ "v5/developer/core-concepts/events",+ "v5/developer/core-concepts/webhooks",+ "v5/developer/core-concepts/translations",+ "v5/developer/core-concepts/slugs",+ "v5/developer/core-concepts/metafields",+ "v5/developer/core-concepts/reports",+ "v5/developer/core-concepts/imports-exports"]}]@@ -1026,16 +1107,16 @@{"group": "Next.js Storefront","pages": [- "developer/storefront/nextjs/quickstart",- "developer/storefront/nextjs/architecture",- "developer/storefront/nextjs/multi-region",- "developer/storefront/nextjs/customization",- "developer/storefront/nextjs/emails",- "developer/storefront/nextjs/wholesale",- "developer/storefront/nextjs/wallet-payments",- "developer/storefront/nextjs/testing",- "developer/storefront/nextjs/environment-variables",- "developer/storefront/nextjs/deployment"+ "v5/developer/storefront/nextjs/quickstart",+ "v5/developer/storefront/nextjs/architecture",+ "v5/developer/storefront/nextjs/multi-region",+ "v5/developer/storefront/nextjs/customization",+ "v5/developer/storefront/nextjs/emails",+ "v5/developer/storefront/nextjs/wholesale",+ "v5/developer/storefront/nextjs/wallet-payments",+ "v5/developer/storefront/nextjs/testing",+ "v5/developer/storefront/nextjs/environment-variables",+ "v5/developer/storefront/nextjs/deployment"]}]@@ -1048,16 +1129,16 @@{"group": "Multi-Tenant / Multi-Store","pages": [- "developer/multi-tenant/quickstart",- "developer/multi-tenant/core-concepts",- "developer/multi-tenant/configuration"+ "v5/developer/multi-tenant/quickstart",+ "v5/developer/multi-tenant/core-concepts",+ "v5/developer/multi-tenant/configuration"]},{"group": "Multi-Vendor Marketplace","pages": [- "developer/multi-vendor/quickstart",- "developer/multi-vendor/installation"+ "v5/developer/multi-vendor/quickstart",+ "v5/developer/multi-vendor/installation"]}]@@ -1070,36 +1151,54 @@{"item": "Extending","icon": "puzzle",- "description": "Customize Checkout, API, and business logic",+ "description": "Customize admin panel, API, and business logic","groups": [{"group": "Tutorial","icon": "graduation-cap","pages": [- "developer/tutorial/introduction",- "developer/tutorial/model",- "developer/tutorial/admin",- "developer/tutorial/extending-models",- "developer/tutorial/api",- "developer/tutorial/events",- "developer/tutorial/sdk",- "developer/tutorial/testing"+ "v5/developer/tutorial/introduction",+ "v5/developer/tutorial/model",+ "v5/developer/tutorial/admin",+ "v5/developer/tutorial/extending-models",+ "v5/developer/tutorial/api",+ "v5/developer/tutorial/events",+ "v5/developer/tutorial/sdk",+ "v5/developer/tutorial/testing"+ ]+ },+ {+ "group": "Admin Panel",+ "icon": "gauge",+ "pages": [+ "v5/developer/admin/admin",+ "v5/developer/admin/extending-ui",+ "v5/developer/admin/navigation",+ "v5/developer/admin/tables",+ "v5/developer/admin/form-builder",+ "v5/developer/admin/components",+ "v5/developer/admin/helper-methods",+ "v5/developer/admin/authentication",+ "v5/developer/admin/custom-javascript",+ "v5/developer/admin/custom-css"]},{- "group": "Backend Customization",+ "group": "Customization Reference","icon": "wrench","pages": [- "v6/developer/customization/quickstart",- "v6/developer/customization/configuration",- "v6/developer/customization/permissions",- "developer/customization/workflows",- "developer/customization/validations",- "v6/developer/customization/api",- "developer/customization/model-preferences",- "developer/customization/metadata",- "v6/developer/customization/dependencies",- "developer/customization/decorators"+ "v5/developer/customization/quickstart",+ "v5/developer/customization/configuration",+ "v5/developer/customization/authentication",+ "v5/developer/customization/checkout",+ "v5/developer/customization/permissions",+ "v5/developer/customization/workflows",+ "v5/developer/customization/dependencies",+ "v5/developer/customization/decorators",+ "v5/developer/customization/model-preferences",+ "v5/developer/customization/metadata",+ "v5/developer/customization/routes",+ "v5/developer/customization/api"]}]@@ -1113,116 +1212,49 @@"group": "Order Routing","icon": "route","pages": [- "developer/how-to/custom-order-routing"+ "v5/developer/how-to/custom-order-routing"]},{"group": "Stock Splitters","icon": "boxes-stacked","pages": [- "developer/how-to/custom-stock-splitter"+ "v5/developer/how-to/custom-stock-splitter"]},{"group": "Payments","icon": "credit-card","pages": [- "developer/how-to/custom-payment-method"+ "v5/developer/how-to/custom-payment-method"]},{"group": "Promotions","icon": "tag","pages": [- "v6/developer/how-to/custom-promotion"- ]- },- {- "group": "Delivery",- "icon": "truck",- "pages": [- "v6/developer/how-to/custom-delivery-rate-provider"- ]- },- {- "group": "Orders",- "icon": "receipt",- "pages": [- "v6/developer/how-to/custom-document-numbers"+ "v5/developer/how-to/custom-promotion"]},{"group": "Reports","icon": "chart-bar","pages": [- "developer/how-to/custom-report"+ "v5/developer/how-to/custom-report"]},{"group": "Search","icon": "search","pages": [- "developer/how-to/custom-search-provider"+ "v5/developer/how-to/custom-search-provider"]},{"group": "Authentication","icon": "key","pages": [- "developer/how-to/custom-api-authentication"- ]- }- ]- },- {- "item": "Dashboard",- "icon": "gauge",- "description": "React dashboard",- "groups": [- {- "group": "Overview",- "pages": [- "developer/dashboard/overview",- "developer/dashboard/concepts"- ]- },- {- "group": "Customization",- "pages": [- "developer/dashboard/customization/quickstart",- "developer/dashboard/customization/navigation",- "developer/dashboard/customization/routes",- "developer/dashboard/customization/slots",- "developer/dashboard/customization/tables",- "developer/dashboard/customization/translations",- "developer/dashboard/customization/permissions",- "developer/dashboard/customization/backend"- ]- },- {- "group": "Recipes",- "pages": [- "developer/dashboard/recipes/attribute-end-to-end",- "developer/dashboard/recipes/custom-form-field",- "developer/dashboard/recipes/page-action-button",- "developer/dashboard/recipes/sidebar-widget"- ]- },- {- "group": "Plugins",- "pages": [- "developer/dashboard/plugins/overview",- "developer/dashboard/plugins/scaffolding",- "developer/dashboard/plugins/publishing",- "developer/dashboard/plugins/distributing"- ]- },- {- "group": "Reference",- "pages": [- "developer/dashboard/public-api",- "developer/dashboard/slots-catalog",- "developer/dashboard/deployment"+ "v5/developer/how-to/custom-api-authentication"]}]@@ -1236,63 +1268,62 @@"group": "Deployment","icon": "server","pages": [- "developer/deployment/quickstart",- "developer/deployment/docker",- "developer/deployment/environment_variables",+ "v5/developer/deployment/quickstart",+ "v5/developer/deployment/docker",+ "v5/developer/deployment/environment_variables",{"group": "AWS","pages": [- "developer/deployment/aws",- "developer/deployment/aws_ecs"+ "v5/developer/deployment/aws",+ "v5/developer/deployment/aws_ecs"]},- "developer/deployment/render",- "developer/deployment/assets",- "developer/deployment/emails",- "developer/deployment/cdn",- "developer/deployment/background_jobs",- "developer/deployment/caching",- "developer/deployment/database",- "developer/deployment/telemetry"+ "v5/developer/deployment/render",+ "v5/developer/deployment/assets",+ "v5/developer/deployment/emails",+ "v5/developer/deployment/cdn",+ "v5/developer/deployment/background_jobs",+ "v5/developer/deployment/caching",+ "v5/developer/deployment/database"]},{"group": "Upgrading","icon": "circle-arrow-up","pages": [- "developer/upgrades/quickstart",+ "v5/developer/upgrades/quickstart",{"group": "Upgrade Guides","pages": [- "developer/upgrades/5.5-to-5.6",- "developer/upgrades/5.4-to-5.5",- "developer/upgrades/5.3-to-5.4",- "developer/upgrades/5.2-to-5.3",- "developer/upgrades/5.1-to-5.2",- "developer/upgrades/5.0-to-5.1",- "developer/upgrades/4.10-to-5.0",- "developer/upgrades/4.9-to-4.10",- "developer/upgrades/4.8-to-4.9",- "developer/upgrades/4.x-to-4.8",- "developer/upgrades/4.6-to-4.7",- "developer/upgrades/4.5-to-4.6",- "developer/upgrades/4.4-to-4.5",- "developer/upgrades/4.3-to-4.4",- "developer/upgrades/4.2-to-4.3",- "developer/upgrades/4.1-to-4.2",- "developer/upgrades/4.0-to-4.1",- "developer/upgrades/3.7-to-4.0",- "developer/upgrades/3.6-to-3.7",- "developer/upgrades/3.5-to-3.6",- "developer/upgrades/3.4-to-3.5",- "developer/upgrades/3.3-to-3.4",- "developer/upgrades/3.2-to-3.3",- "developer/upgrades/3.1-to-3.2",- "developer/upgrades/3.0-to-3.1",- "developer/upgrades/2.3-to-2.4",- "developer/upgrades/2.2-to-2.3",- "developer/upgrades/2.1-to-2.2",- "developer/upgrades/2.0-to-2.1"+ "v5/developer/upgrades/5.5-to-5.6",+ "v5/developer/upgrades/5.4-to-5.5",+ "v5/developer/upgrades/5.3-to-5.4",+ "v5/developer/upgrades/5.2-to-5.3",+ "v5/developer/upgrades/5.1-to-5.2",+ "v5/developer/upgrades/5.0-to-5.1",+ "v5/developer/upgrades/4.10-to-5.0",+ "v5/developer/upgrades/4.9-to-4.10",+ "v5/developer/upgrades/4.8-to-4.9",+ "v5/developer/upgrades/4.x-to-4.8",+ "v5/developer/upgrades/4.6-to-4.7",+ "v5/developer/upgrades/4.5-to-4.6",+ "v5/developer/upgrades/4.4-to-4.5",+ "v5/developer/upgrades/4.3-to-4.4",+ "v5/developer/upgrades/4.2-to-4.3",+ "v5/developer/upgrades/4.1-to-4.2",+ "v5/developer/upgrades/4.0-to-4.1",+ "v5/developer/upgrades/3.7-to-4.0",+ "v5/developer/upgrades/3.6-to-3.7",+ "v5/developer/upgrades/3.5-to-3.6",+ "v5/developer/upgrades/3.4-to-3.5",+ "v5/developer/upgrades/3.3-to-3.4",+ "v5/developer/upgrades/3.2-to-3.3",+ "v5/developer/upgrades/3.1-to-3.2",+ "v5/developer/upgrades/3.0-to-3.1",+ "v5/developer/upgrades/2.3-to-2.4",+ "v5/developer/upgrades/2.2-to-2.3",+ "v5/developer/upgrades/2.1-to-2.2",+ "v5/developer/upgrades/2.0-to-2.1"]}]@@ -1301,17 +1332,17 @@"group": "Contributing","icon": "heart","pages": [- "developer/contributing/quickstart",- "developer/contributing/developing-spree",- "developer/contributing/creating-an-extension"+ "v5/developer/contributing/quickstart",+ "v5/developer/contributing/developing-spree",+ "v5/developer/contributing/creating-an-extension"]},{"group": "Security","icon": "shield","pages": [- "developer/security/security_policy",- "developer/security/pci_compliance"+ "v5/developer/security/security_policy",+ "v5/developer/security/pci_compliance"]}]@@ -1329,21 +1360,21 @@{"group": "Getting Started","pages": [- "developer/sdk/quickstart",- "developer/sdk/authentication",- "developer/sdk/configuration",- "developer/sdk/extending"+ "v5/developer/sdk/quickstart",+ "v5/developer/sdk/authentication",+ "v5/developer/sdk/configuration",+ "v5/developer/sdk/extending"]},{"group": "Store API","pages": [- "developer/sdk/store/products",- "developer/sdk/store/cart-checkout",- "developer/sdk/store/payments",- "developer/sdk/store/markets",- "developer/sdk/store/account",- "developer/sdk/store/wishlists"+ "v5/developer/sdk/store/products",+ "v5/developer/sdk/store/cart-checkout",+ "v5/developer/sdk/store/payments",+ "v5/developer/sdk/store/markets",+ "v5/developer/sdk/store/account",+ "v5/developer/sdk/store/wishlists"]}]@@ -1356,11 +1387,11 @@{"group": "Admin SDK","pages": [- "developer/sdk/admin/quickstart",- "developer/sdk/admin/authentication",- "developer/sdk/admin/resources",- "developer/sdk/admin/querying-and-errors",- "developer/sdk/admin/extending"+ "v5/developer/sdk/admin/quickstart",+ "v5/developer/sdk/admin/authentication",+ "v5/developer/sdk/admin/resources",+ "v5/developer/sdk/admin/querying-and-errors",+ "v5/developer/sdk/admin/extending"]}]@@ -1373,8 +1404,8 @@{"group": "CLI","pages": [- "developer/cli/quickstart",- "developer/cli/admin-api"+ "v5/developer/cli/quickstart",+ "v5/developer/cli/admin-api"]}]@@ -1387,7 +1418,7 @@{"group": "create-spree-app","pages": [- "developer/create-spree-app/quickstart"+ "v5/developer/create-spree-app/quickstart"]}]@@ -1400,10 +1431,10 @@{"group": "Agentic Development","pages": [- "developer/agentic/overview",- "developer/agentic/agent-skills",- "developer/agentic/mcp",- "developer/agentic/llm-docs"+ "v5/developer/agentic/overview",+ "v5/developer/agentic/agent-skills",+ "v5/developer/agentic/mcp",+ "v5/developer/agentic/llm-docs"]}]@@ -1578,28 +1609,28 @@{"group": "Introduction","pages": [- "user/what-is-spree-commerce",- "user/using-spree",- "user/user-quickstart-guide"+ "v5/user/what-is-spree-commerce",+ "v5/user/using-spree",+ "v5/user/user-quickstart-guide"]},{"group": "Migration","pages": [- "user/migration/migrate-from-shopify"+ "v5/user/migration/migrate-from-shopify"]},{"group": "How-to Guides","pages": [- "user/how-to/multi-currency-pricing",- "user/how-to/multiple-languages",- "user/how-to/multi-region-pricing",- "user/how-to/wholesale-pricing",- "user/how-to/volume-pricing",- "user/how-to/regional-wholesale",- "user/how-to/regional-volume",- "user/how-to/schedule-sale-pricing"+ "v5/user/how-to/multi-currency-pricing",+ "v5/user/how-to/multiple-languages",+ "v5/user/how-to/multi-region-pricing",+ "v5/user/how-to/wholesale-pricing",+ "v5/user/how-to/volume-pricing",+ "v5/user/how-to/regional-wholesale",+ "v5/user/how-to/regional-volume",+ "v5/user/how-to/schedule-sale-pricing"]},{@@ -1608,29 +1639,29 @@{"group": "Create & Edit Products","pages": [- "user/products/creating-products",- "user/products/deleting-products",- "user/products/editing-products",- "user/products/editing-multi-variant-products",- "user/products/cloning-products"+ "v5/user/products/creating-products",+ "v5/user/products/deleting-products",+ "v5/user/products/editing-products",+ "v5/user/products/editing-multi-variant-products",+ "v5/user/products/cloning-products"]},{"group": "Manage Products","pages": [- "user/manage-products/search-products",- "user/manage-products/bulk-product-operations",- "user/manage-products/price-lists",- "user/manage-products/export-products",- "user/manage-products/import-products",- "user/manage-products/multi-currency-import-export",- "user/manage-products/product-import-file-template",- "user/manage-products/translations",- "user/manage-products/stock-levels",- "user/manage-products/stock-transfers",- "user/manage-products/product-taxonomies",- "user/manage-products/product-options",- "user/manage-products/product-metafields"+ "v5/user/manage-products/search-products",+ "v5/user/manage-products/bulk-product-operations",+ "v5/user/manage-products/price-lists",+ "v5/user/manage-products/export-products",+ "v5/user/manage-products/import-products",+ "v5/user/manage-products/multi-currency-import-export",+ "v5/user/manage-products/product-import-file-template",+ "v5/user/manage-products/translations",+ "v5/user/manage-products/stock-levels",+ "v5/user/manage-products/stock-transfers",+ "v5/user/manage-products/product-taxonomies",+ "v5/user/manage-products/product-options",+ "v5/user/manage-products/product-metafields"]}]@@ -1638,80 +1669,80 @@{"group": "Orders","pages": [- "user/orders/order-states",- "user/orders/processing-orders",- "user/orders/creating-orders",- "user/orders/editing-orders",- "user/orders/order-adjustments",- "user/orders/exporting-orders",- "user/orders/cancelling-orders",- "user/orders/refunding-orders",- "user/orders/searching-orders"+ "v5/user/orders/order-states",+ "v5/user/orders/processing-orders",+ "v5/user/orders/creating-orders",+ "v5/user/orders/editing-orders",+ "v5/user/orders/order-adjustments",+ "v5/user/orders/exporting-orders",+ "v5/user/orders/cancelling-orders",+ "v5/user/orders/refunding-orders",+ "v5/user/orders/searching-orders"]},{"group": "Returns","pages": [- "v6/user/settings/returns-configuration",- "v6/user/returns/returns-processing"+ "v5/user/settings/returns-configuration",+ "v5/user/returns/returns-processing"]},{"group": "Customers","pages": [- "user/customers/create-customer",- "user/customers/customer-profile",- "user/customers/edit-customer",- "user/customers/issue-gift-card",- "user/customers/assign-store-credits",- "user/customers/searching-customers",- "user/customers/exporting-customers",- "user/customers/customer-groups"+ "v5/user/customers/create-customer",+ "v5/user/customers/customer-profile",+ "v5/user/customers/edit-customer",+ "v5/user/customers/issue-gift-card",+ "v5/user/customers/assign-store-credits",+ "v5/user/customers/searching-customers",+ "v5/user/customers/exporting-customers",+ "v5/user/customers/customer-groups"]},{"group": "Promotions","pages": [- "user/promotions/create-a-promotion",- "user/promotions/promotion-rules",- "user/promotions/promotion-actions",- "user/promotions/gift-cards"+ "v5/user/promotions/create-a-promotion",+ "v5/user/promotions/promotion-rules",+ "v5/user/promotions/promotion-actions",+ "v5/user/promotions/gift-cards"]},{"group": "Vendors","pages": [- "user/settings/marketplace",- "user/vendors/vendor-onboarding-shopify",- "user/vendors/vendor-onboarding-woocommerce",- "user/vendors/vendor-onboarding-manual",- "user/vendors/vendor-management",- "user/vendors/commission-rates",- "user/vendors/vendor-payouts",- "user/vendors/multi-vendor-checkout"+ "v5/user/settings/marketplace",+ "v5/user/vendors/vendor-onboarding-shopify",+ "v5/user/vendors/vendor-onboarding-woocommerce",+ "v5/user/vendors/vendor-onboarding-manual",+ "v5/user/vendors/vendor-management",+ "v5/user/vendors/commission-rates",+ "v5/user/vendors/vendor-payouts",+ "v5/user/vendors/multi-vendor-checkout"]},{"group": "Settings","pages": [- "user/settings/store-details",- "user/settings/sales-channels",- "user/settings/users",- "user/settings/emails",- "user/settings/policies",- "user/settings/payments",- "user/settings/markets",- "user/settings/zones",- "user/settings/shipping-methods",- "user/settings/tax",- "user/settings/locations",- "user/settings/metafields"+ "v5/user/settings/store-details",+ "v5/user/settings/sales-channels",+ "v5/user/settings/users",+ "v5/user/settings/emails",+ "v5/user/settings/policies",+ "v5/user/settings/payments",+ "v5/user/settings/markets",+ "v5/user/settings/zones",+ "v5/user/settings/shipping-methods",+ "v5/user/settings/tax",+ "v5/user/settings/locations",+ "v5/user/settings/metafields"]},{"group": "Security","pages": [- "user/security"+ "v5/user/security"]}]diff --git a/docs/index.mdx b/docs/index.mdxindex 8f855c08e0..7e5a2c0e25 100644--- a/docs/index.mdx+++ b/docs/index.mdx@@ -1,426 +1,333 @@---title: "Spree Commerce documentation: open-source commerce platform"-description: "Spree is the open-source commerce engine that adapts to your stack, business model, and scale — from the first sale to global multi-channel growth."+description: "Spree is the open-source commerce platform that fits the systems you already run — connect your ERP, PIM, WMS and payment stack instead of replacing them."mode: "custom"----{/* ── Icon components (Lucide SVG paths) ── */}+{/* ── Primitives ─────────────────────────────────────────────────────────── */}export const Icon = ({ children, className = "" }) => (- <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"- fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"+ fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"className={className}>{children}</svg>);-{/* ── Quick Start card ── */}--export const QuickStartCard = ({ icon, title, description, href, tag }) => (- <a href={href}- className="group relative flex flex-col gap-3 rounded-xl bg-white dark:bg-transparent border border-gray-200 dark:border-zinc-800 p-5 hover:border-blue-200 dark:hover:border-zinc-700 hover:shadow-sm transition-all no-underline">- <div className="flex items-center gap-3">- <div className="flex items-center justify-center w-10 h-10 rounded-lg bg-gray-100 dark:bg-zinc-800 text-gray-600 dark:text-zinc-400 group-hover:bg-blue-50 group-hover:text-blue-600 dark:group-hover:bg-blue-950 dark:group-hover:text-blue-400 transition-colors">- {icon}- </div>- <div className="flex items-center gap-2">- <h3 className="text-base font-semibold text-gray-900 dark:text-zinc-50 m-0">{title}</h3>- {tag && <span className="text-xs font-medium px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300">{tag}</span>}- </div>- </div>- <p className="text-sm text-gray-500 dark:text-zinc-400 m-0 leading-relaxed">{description}</p>- </a>+export const Eyebrow = ({ children }) => (+ <div className="font-mono text-xs uppercase tracking-[0.14em] text-[#999999] dark:text-zinc-500 mb-3">+ {children}+ </div>);-{/* ── Concept grid item ── */}+export const SectionTitle = ({ children }) => (+ <h2 className="text-3xl sm:text-4xl font-semibold tracking-tight text-[#061932] dark:text-zinc-50 m-0">+ {children}+ </h2>+);-export const ConceptItem = ({ icon, title, href }) => (- <a href={href}- className="group flex items-center gap-3 rounded-lg bg-white dark:bg-transparent border border-gray-100 dark:border-zinc-800/50 px-3.5 py-3 hover:border-blue-100 dark:hover:border-zinc-700 dark:hover:bg-zinc-800/50 transition-all no-underline">- <div className="flex items-center justify-center w-8 h-8 rounded-md bg-gray-100 group-hover:bg-blue-50 dark:bg-zinc-800 dark:group-hover:bg-zinc-800 text-gray-500 dark:text-zinc-400 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors shrink-0">- {icon}- </div>- <span className="text-sm font-medium text-gray-700 dark:text-zinc-300 group-hover:text-blue-700 dark:group-hover:text-zinc-100 transition-colors">{title}</span>- </a>+export const Lede = ({ children }) => (+ <p className="mt-3 text-base text-[#666666] dark:text-zinc-400 leading-relaxed m-0">{children}</p>);-{/* ── Use case card ── */}+export const Section = ({ children, className = "" }) => (+ <section className={`border-t border-[#e9e5dd]/80 dark:border-[#3f3e3c] ${className}`}>+ <div className="max-w-7xl mx-auto px-6 sm:px-10 py-16 sm:py-20">{children}</div>+ </section>+);-export const UseCaseCard = ({ icon, title, description, href }) => (+{/* Big clickable card — the whole surface is the link. */}+export const Card = ({ href, icon, title, children, footer }) => (<a href={href}- className="group flex flex-col gap-2 rounded-xl bg-white dark:bg-transparent border border-gray-200 dark:border-zinc-800 p-5 hover:border-blue-200 dark:hover:border-zinc-700 hover:shadow-sm transition-all no-underline">- <div className="flex items-center justify-center w-9 h-9 rounded-lg bg-gray-100 dark:bg-zinc-800 text-gray-500 dark:text-zinc-400 group-hover:bg-blue-50 group-hover:text-blue-600 dark:group-hover:text-blue-400 dark:group-hover:bg-zinc-800 transition-colors">- {icon}+ className="group flex flex-col rounded-2xl border border-[#e2dfd8] dark:border-[#3f3e3c] bg-[#f7f5f2] dark:bg-[#272626] p-7 no-underline transition-colors hover:border-[#d5d5d5] dark:hover:border-[#565351] hover:bg-[#f2efea] dark:hover:bg-[#2e2c2c]">+ <div className="flex items-center gap-3">+ {icon && (+ <span className="flex items-center justify-center w-9 h-9 rounded-lg bg-white dark:bg-[#3f3e3c] text-[#4d4d4d] dark:text-zinc-300 shrink-0">+ {icon}+ </span>+ )}+ <h3 className="text-lg font-semibold text-[#061932] dark:text-zinc-50 m-0">{title}</h3></div>- <h4 className="text-sm font-semibold text-gray-900 dark:text-zinc-50 m-0">{title}</h4>- <p className="text-xs text-gray-500 dark:text-zinc-400 m-0 leading-relaxed">{description}</p>+ <p className="mt-3 text-sm text-[#666666] dark:text-zinc-400 leading-relaxed m-0">{children}</p>+ {footer}</a>);-{/* ── Integration logo ── */}+{/* Numbered step list inside a learning-path card. */}+export const Steps = ({ items }) => (+ <ol className="mt-5 pt-5 border-t border-[#e9e5dd] dark:border-[#3f3e3c] list-none p-0 m-0 space-y-2.5">+ {items.map((label, i) => (+ <li key={label} className="flex items-center gap-3 m-0">+ <span className="flex items-center justify-center w-5 h-5 shrink-0 rounded-full bg-white dark:bg-[#3f3e3c] text-[11px] font-medium text-[#666666] dark:text-zinc-400">+ {i + 1}+ </span>+ <span className="text-sm text-[#4d4d4d] dark:text-zinc-300">{label}</span>+ </li>+ ))}+ </ol>+);-export const IntegrationItem = ({ icon, name, href }) => (+{/* Pill link — used for the "How do I…?" question list. */}+export const Pill = ({ href, children }) => (<a href={href}- className="group flex flex-col items-center gap-2 rounded-lg p-3 hover:bg-blue-50 dark:hover:bg-zinc-800/50 transition-colors no-underline">- <div className="flex items-center justify-center w-10 h-10 rounded-lg border border-gray-200 dark:border-zinc-700 bg-white dark:bg-zinc-800 text-gray-500 dark:text-zinc-400 group-hover:border-blue-100 dark:group-hover:border-zinc-600 transition-colors">- {icon}- </div>- <span className="text-xs font-medium text-gray-600 dark:text-zinc-400 group-hover:text-blue-600">{name}</span>+ className="inline-flex items-center rounded-lg border border-[#e2dfd8] dark:border-[#3f3e3c] bg-[#f7f5f2] dark:bg-[#272626] px-3.5 py-2 font-mono text-[13px] text-[#4d4d4d] dark:text-zinc-300 no-underline transition-colors hover:border-[#b3b3b3] dark:hover:border-[#5f5c59] hover:text-[#061932] dark:hover:text-zinc-100">+ {children}</a>);-{/* ── Section heading ── */}--export const SectionHeading = ({ title, description }) => (- <div className="mb-6">- <h2 className="text-xl font-semibold text-gray-900 dark:text-zinc-50 m-0">{title}</h2>- {description && <p className="text-sm text-gray-500 dark:text-zinc-400 mt-1 m-0">{description}</p>}- </div>+{/* Opens Mintlify's own search modal via the hidden sidebar entry, which is+ still mounted on custom-mode pages — no imitation search, the real one. */}+export const SearchBox = () => (+ <button+ onClick={() => document.getElementById('search-bar-entry')?.click()}+ className="flex w-full max-w-xl items-center justify-between gap-3 rounded-xl border border-[#e2dfd8] dark:border-[#3f3e3c] bg-[#f7f5f2] dark:bg-[#272626] px-4 h-12 text-left cursor-pointer transition-colors hover:border-[#d5d5d5] dark:hover:border-[#565351]">+ <span className="flex items-center gap-2.5 text-[#999999] dark:text-zinc-500">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" />+ </svg>+ <span className="text-[15px]">Search the docs...</span>+ </span>+ <kbd className="rounded-md border border-[#e2dfd8] dark:border-[#4a4846] px-1.5 py-0.5 font-mono text-xs text-[#999999] dark:text-zinc-500">⌘K</kbd>+ </button>);-{/* ── Resource link ── */}--export const ResourceLink = ({ icon, title, description, href }) => (+{/* Compact concept link — Saleor-style topic + one-line descriptor. */}+export const ConceptLink = ({ href, title, children }) => (<a href={href}- className="group flex items-start gap-3 rounded-lg p-3 border border-transparent hover:bg-gray-50 hover:border-blue-300 dark:hover:bg-zinc-800/50 dark:hover:border-zinc-300 transition-colors no-underline">- <div className="flex items-center justify-center w-8 h-8 rounded-md text-gray-400 dark:text-zinc-500 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors shrink-0 mt-0.5">- {icon}- </div>- <div>- <div className="text-sm font-medium text-gray-700 dark:text-zinc-300 group-hover:text-gray-900 dark:group-hover:text-zinc-100 transition-colors">{title}</div>- <div className="text-xs text-gray-500 dark:text-zinc-500 mt-0.5">{description}</div>- </div>+ className="group block rounded-xl px-4 py-3.5 no-underline transition-colors hover:bg-[#f7f5f2] dark:hover:bg-[#32302e]/60">+ <span className="inline-flex items-center gap-1.5 text-[15px] font-semibold text-[#061932] dark:text-zinc-50">+ {title}+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"+ strokeLinecap="round" strokeLinejoin="round"+ className="opacity-0 -translate-x-1 transition-all group-hover:opacity-100 group-hover:translate-x-0">+ <path d="M5 12h14" /><path d="m12 5 7 7-7 7" />+ </svg>+ </span>+ <span className="block mt-1 text-sm text-[#666666] dark:text-zinc-400 leading-relaxed">{children}</span></a>);-{/* ── Small icons (16×16) ── */}--export const SmallIcon = ({ children, className = "" }) => (- <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"- fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"- className={className}>- {children}- </svg>-);--{/* ── Copy-to-clipboard install command ── */}--export const CopyCommand = ({ command }) => {+export const CopyBox = ({ label, command }) => {const [copied, setCopied] = useState(false);- const handleCopy = () => {- navigator.clipboard.writeText(command);- setCopied(true);- setTimeout(() => setCopied(false), 2000);- };return (- <button onClick={handleCopy}- className="group/copy inline-flex items-center gap-3 rounded-lg bg-gray-950 dark:bg-zinc-800 pl-5 pr-3 py-3 h-12 font-mono text-sm text-gray-100 border-0 cursor-pointer hover:bg-gray-900 dark:hover:bg-zinc-700 transition-colors">- <span className="text-gray-500 select-none">$</span>- <span>{command}</span>- <span className="ml-2 flex items-center justify-center w-8 h-8 rounded-md text-gray-400 hover:text-gray-200 transition-colors"- title="Copy to clipboard">- {copied ? (- <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#4ade80" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5" /></svg>- ) : (- <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2" /><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" /></svg>- )}- </span>- </button>+ <div>+ <div className="font-mono text-xs uppercase tracking-[0.14em] text-[#999999] dark:text-zinc-500 mb-2">{label}</div>+ <button+ onClick={() => { navigator.clipboard.writeText(command); setCopied(true); setTimeout(() => setCopied(false), 2000); }}+ className="group/copy flex w-full items-center justify-between gap-4 rounded-xl border border-[#e2dfd8] dark:border-[#3f3e3c] bg-[#f7f5f2] dark:bg-[#272626] px-4 py-3.5 text-left cursor-pointer transition-colors hover:border-[#d5d5d5] dark:hover:border-[#565351]">+ <span className="font-mono text-[13px] leading-relaxed text-[#1a1a1a] dark:text-zinc-200 break-all">{command}</span>+ <span className="shrink-0 text-[#999999] group-hover/copy:text-[#666666] dark:group-hover/copy:text-zinc-300">+ {copied+ ? <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#22c55e" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5" /></svg>+ : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2" /><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" /></svg>}+ </span>+ </button>+ </div>);};-{/* ════════════════════════════════════════════════════════════════════════- PAGE CONTENT- ════════════════════════════════════════════════════════════════════════ */}--<div className="relative max-w-5xl mx-auto px-4 py-16">-- {/* ── HERO ── */}- <div className="text-center mb-16">- <h1 className="text-4xl sm:text-5xl font-bold text-gray-900 dark:text-zinc-50 tracking-tight m-0">- Spree Documentation- </h1>- <p className="max-w-2xl mx-auto mt-4 text-lg text-gray-500 dark:text-zinc-400">- The open-source commerce engine that adapts to your stack, your business model, and your scale.- </p>- <div className="mt-8 flex flex-col items-center gap-5">- <div className="flex flex-col sm:flex-row items-center gap-4 sm:gap-5">- <div className="flex flex-col items-center gap-1.5">+{/* ── Page ───────────────────────────────────────────────────────────────── */}++<div className="w-full">++ {/* HERO */}+ <section>+ <div className="max-w-7xl mx-auto px-6 sm:px-10 pt-20 pb-16 sm:pt-28 sm:pb-20">+ <div className="max-w-3xl">+ <h1 className="text-4xl sm:text-6xl font-semibold tracking-tight text-[#061932] dark:text-zinc-50 m-0 leading-[1.05]">+ Build commerce that fits your stack+ </h1>+ <p className="mt-6 text-lg sm:text-xl text-[#666666] dark:text-zinc-400 leading-relaxed m-0">+ Spree is an open-source commerce platform with a REST API, TypeScript SDKs and a React+ dashboard. Self-hosted, extensible, and built to connect the systems you already run.+ </p>+ <div className="mt-8">+ <SearchBox />+ </div>+ <div className="mt-6 flex flex-wrap items-center gap-3">+ <a href="/developer/getting-started/quickstart"+ className="inline-flex items-center gap-2 rounded-xl bg-[#0077ff] hover:bg-[#0060ce] px-6 py-3.5 text-base font-medium text-white no-underline transition-colors">+ Get started+ <Icon className="w-4 h-4"><path d="M5 12h14" /><path d="m12 5 7 7-7 7" /></Icon>+ </a><a href="https://console.spree.sh"- className="inline-flex items-center gap-2 rounded-xl bg-blue-600 hover:bg-blue-700 px-6 py-4 text-base font-semibold text-white no-underline transition-colors h-12">- <SmallIcon><path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z" /></SmallIcon>+ className="inline-flex items-center gap-2 rounded-xl border border-[#d5d5d5] dark:border-[#4a4846] px-6 py-3.5 text-base font-medium text-[#1a1a1a] dark:text-zinc-200 no-underline transition-colors hover:border-[#b3b3b3] dark:hover:border-[#5f5c59]">Launch a free sandbox</a>- <span className="text-xs text-gray-400 dark:text-zinc-500">Hosted store — nothing to install</span></div>- <span className="text-sm text-gray-400 dark:text-zinc-500 select-none sm:pb-5">or</span>- <div className="flex flex-col items-center gap-1.5">- <CopyCommand command="npx create-spree-app@latest my-store" />- <span className="text-xs text-gray-400 dark:text-zinc-500">- Run locally with Docker · <a href="/docs/developer/getting-started/quickstart" className="text-gray-500 dark:text-zinc-400 hover:text-blue-600 dark:hover:text-zinc-200 underline underline-offset-2 decoration-gray-300 dark:decoration-zinc-600 transition-colors">more options</a>- </span>+ <div className="mt-8 max-w-xl">+ <CopyBox label="Or run it locally" command="npx create-spree-app@latest my-store" /></div></div></div>- </div>-- {/* ── SECTION 1: QUICK START PATHS ── */}- <div className="mb-16">- <SectionHeading title="Get Started" description="Choose the path that matches how you work" />- <div className="grid sm:grid-cols-2 gap-4">- <QuickStartCard- href="/developer/storefront/nextjs/quickstart"- tag="Popular"- icon={<Icon><rect width="18" height="18" x="3" y="3" rx="2" /><path d="m10 8 4 4-4 4" /></Icon>}- title="Build a Storefront"- description="Start with Next.js and our TypeScript SDK. Build a custom frontend connected to Spree's API."- />- <QuickStartCard- href="/developer/tutorial/introduction"- icon={<Icon><path d="M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" /><path d="M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z" /></Icon>}- title="Extend the Framework"- description="Customize models, admin UI, and business logic. Full access to the platform internals."- />- <QuickStartCard- href="/api-reference"- icon={<Icon><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4" /><path d="M3 5v14a2 2 0 0 0 2 2h16v-5" /><path d="M18 12a2 2 0 0 0 0 4h4v-4z" /></Icon>}- title="Explore the API"- description="REST API with OpenAPI spec, filtering, pagination, and TypeScript types."- />- <QuickStartCard- href="/developer/core-concepts/architecture"+ </section>++ {/* LEARNING PATHS */}+ <Section className="home-band">+ <Eyebrow>Learning paths</Eyebrow>+ <SectionTitle>Start where you are</SectionTitle>+ <div className="mt-10 grid md:grid-cols-3 gap-5">+ <Card href="/developer/storefront/nextjs/quickstart"+ icon={<Icon><path d="m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7" /><path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8" /><rect width="20" height="5" x="2" y="7" /></Icon>}+ title="Build a storefront"+ footer={<Steps items={["Set up the TypeScript SDK", "Fetch products and build a cart", "Take a payment at checkout", "Deploy the Next.js starter"]} />}>+ Use the Store API to power any frontend — Next.js, a mobile app, or your own stack.+ </Card>+ <Card href="/developer/tutorial/introduction"+ icon={<Icon><path d="M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" /><path d="M18.4 2.6a1 1 0 0 1 3 3l-9 9a2 2 0 0 1-.9.5l-2.9.9a.5.5 0 0 1-.6-.6l.8-2.9a2 2 0 0 1 .5-.9z" /></Icon>}+ title="Extend the platform"+ footer={<Steps items={["Model a custom resource", "Add an Admin API endpoint", "Build a dashboard plugin", "Expose it on the storefront"]} />}>+ Add your own models, endpoints and admin screens without forking the core.+ </Card>+ <Card href="/developer/core-concepts/architecture"icon={<Icon><circle cx="12" cy="12" r="10" /><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20" /><path d="M2 12h20" /></Icon>}title="Evaluate Spree"- description="Architecture overview, use cases, and platform capabilities. Ideal for technical decision makers."- />- <QuickStartCard- href="/developer/agentic/overview"- tag="New"- icon={<Icon><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z" /><path d="M20 3v4" /><path d="M22 5h-4" /><path d="M4 17v2" /><path d="M5 18H3" /></Icon>}- title="Build with AI Agents"- description="Agent skills, a docs MCP server, and LLM-ready documentation for Claude Code, Cursor, Copilot, and 60+ other tools."- />- <QuickStartCard- href="/developer/tutorial/api"- icon={<Icon><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4" /><path d="M3 5v14a2 2 0 0 0 2 2h16v-5" /><path d="M18 12a2 2 0 0 0 0 4h4v-4z" /></Icon>}- title="Add Custom Resources"- description="Generate a complete model + Store and Admin API surface with one command."- />+ footer={<Steps items={["Read the architecture overview", "See how it fits your systems", "Review deployment options", "Plan your upgrade path"]} />}>+ Assess the architecture, the integration story and what running it in production takes.+ </Card></div>- </div>-- {/* ── SECTION 2: COMMERCE BUILDING BLOCKS ── */}- <div className="mb-16">- <SectionHeading title="Commerce Building Blocks" description="Explore core commerce concepts that power your store" />-- <div className="space-y-6">+ </Section>++ {/* CORE CONCEPTS */}+ <Section>+ <Eyebrow>Core concepts</Eyebrow>+ <SectionTitle>Understand the platform</SectionTitle>+ <div className="mt-8 grid sm:grid-cols-2 lg:grid-cols-3 gap-x-6 gap-y-1 -mx-4">+ <ConceptLink href="/developer/core-concepts/products" title="Products">+ Catalog, variants, options and categories.+ </ConceptLink>+ <ConceptLink href="/developer/core-concepts/pricing" title="Pricing">+ Price lists, multi-currency and customer-group pricing.+ </ConceptLink>+ <ConceptLink href="/developer/core-concepts/carts" title="Carts & checkout">+ The cart lifecycle from first item to completed order.+ </ConceptLink>+ <ConceptLink href="/developer/core-concepts/orders" title="Orders">+ Statuses, editing, cancellation and refunds.+ </ConceptLink>+ <ConceptLink href="/developer/core-concepts/payments" title="Payments">+ Gateways, authorization, capture and payment sessions.+ </ConceptLink>+ <ConceptLink href="/developer/core-concepts/fulfillments" title="Fulfillments">+ Delivery methods, labels, tracking and pickup.+ </ConceptLink>+ <ConceptLink href="/developer/core-concepts/markets" title="Markets">+ Sell across regions with their own currency, locale and tax.+ </ConceptLink>+ <ConceptLink href="/developer/core-concepts/promotions" title="Promotions">+ Rules, actions, coupon codes and gift cards.+ </ConceptLink>+ <ConceptLink href="/developer/core-concepts/events" title="Events & webhooks">+ React to what happens in the store, inside and outside the app.+ </ConceptLink>+ </div>+ </Section>- {/* Catalog */}+ {/* FITS YOUR ARCHITECTURE */}+ <Section className="home-band">+ <div className="grid lg:grid-cols-[1fr_1.15fr] gap-12 lg:gap-16 items-start"><div>- <div className="text-xs font-semibold uppercase tracking-wider text-gray-400 dark:text-zinc-500 mb-2 px-1">Catalog</div>- <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">- <ConceptItem href="/developer/core-concepts/products"- icon={<SmallIcon><path d="m7.5 4.27 9 5.15" /><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z" /><path d="m3.3 7 8.7 5 8.7-5" /><path d="M12 22V12" /></SmallIcon>}- title="Products" />- <ConceptItem href="/developer/core-concepts/pricing"- icon={<SmallIcon><line x1="12" x2="12" y1="2" y2="22" /><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" /></SmallIcon>}- title="Pricing" />- <ConceptItem href="/developer/core-concepts/inventory"- icon={<SmallIcon><path d="M16 16h6" /><path d="M19 13v6" /><path d="M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14" /><path d="m7.5 4.27 9 5.15" /><path d="M3.3 7 12 12l8.7-5" /><path d="M12 22V12" /></SmallIcon>}- title="Inventory" />- <ConceptItem href="/developer/core-concepts/media"- icon={<SmallIcon><rect width="18" height="18" x="3" y="3" rx="2" ry="2" /><circle cx="9" cy="9" r="2" /><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" /></SmallIcon>}- title="Media" />- </div>+ <Eyebrow>Integrations</Eyebrow>+ <SectionTitle>Spree fits your architecture</SectionTitle>+ <Lede>+ Most teams already run an ERP for stock, a PIM for product data and a payment provider with+ years of history. Spree is the system of record for what the shopper sees — your systems stay+ the system of record for what is true.+ </Lede>+ <a href="/developer/providers/overview"+ className="mt-6 inline-flex items-center gap-2 text-sm font-medium text-blue-600 dark:text-blue-400 no-underline hover:gap-3 transition-all">+ See how the provider contracts work+ <Icon className="w-4 h-4"><path d="M5 12h14" /><path d="m12 5 7 7-7 7" /></Icon>+ </a></div>-- {/* Cart & Checkout */}- <div>- <div className="text-xs font-semibold uppercase tracking-wider text-gray-400 dark:text-zinc-500 mb-2 px-1">Cart & Checkout</div>- <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">- <ConceptItem href="/developer/core-concepts/orders"- icon={<SmallIcon><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z" /><path d="M3 6h18" /><path d="M16 10a4 4 0 0 1-8 0" /></SmallIcon>}- title="Orders" />- <ConceptItem href="/developer/core-concepts/payments"- icon={<SmallIcon><rect width="20" height="14" x="2" y="5" rx="2" /><line x1="2" x2="22" y1="10" y2="10" /></SmallIcon>}- title="Payments" />- <ConceptItem href="/developer/core-concepts/taxes"- icon={<SmallIcon><path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z" /><path d="m9.5 14.5 5-5" /></SmallIcon>}- title="Taxes" />- <ConceptItem href="/developer/core-concepts/promotions"- icon={<SmallIcon><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z" /><path d="M12 9v4" /><path d="M12 17h.01" /></SmallIcon>}- title="Promotions" />- </div>+ <div className="grid sm:grid-cols-2 gap-4">+ <Card href="/developer/providers/erp" title="ERP">Sync stock levels and keep inventory truth where it already lives.</Card>+ <Card href="/developer/providers/pim" title="PIM">Feed product data and pricing from your catalog system.</Card>+ <Card href="/developer/providers/fulfillment" title="WMS & carriers">Buy labels, push fulfillments and track parcels.</Card>+ <Card href="/developer/providers/sso" title="Identity & SSO">OpenID Connect for staff and customer sign-in.</Card></div>+ </div>+ </Section>- {/* Fulfillment */}+ {/* HOW DO I…? */}+ <Section>+ <div className="grid lg:grid-cols-[1fr_1.3fr] gap-12 lg:gap-16 items-start"><div>- <div className="text-xs font-semibold uppercase tracking-wider text-gray-400 dark:text-zinc-500 mb-2 px-1">Fulfillment</div>- <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">- <ConceptItem href="/developer/core-concepts/shipments"- icon={<SmallIcon><path d="M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2" /><path d="M15 18H9" /><path d="M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14" /><circle cx="17" cy="18" r="2" /><circle cx="7" cy="18" r="2" /></SmallIcon>}- title="Shipments" />- <ConceptItem href="/developer/core-concepts/addresses"- icon={<SmallIcon><path d="M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0" /><circle cx="12" cy="10" r="3" /></SmallIcon>}- title="Addresses" />- <ConceptItem href="/developer/core-concepts/calculators"- icon={<SmallIcon><rect width="16" height="20" x="4" y="2" rx="2" /><line x1="8" x2="16" y1="6" y2="6" /><line x1="16" x2="16" y1="14" y2="18" /><path d="M16 10h.01" /><path d="M12 10h.01" /><path d="M8 10h.01" /><path d="M12 14h.01" /><path d="M8 14h.01" /><path d="M12 18h.01" /><path d="M8 18h.01" /></SmallIcon>}- title="Calculators" />- <ConceptItem href="/developer/core-concepts/adjustments"- icon={<SmallIcon><path d="M12 20h9" /><path d="M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z" /></SmallIcon>}- title="Adjustments" />- </div>+ <Eyebrow>How to</Eyebrow>+ <SectionTitle>How do I…?</SectionTitle>+ <Lede>Task-focused guides for the most common things teams build with Spree.</Lede></div>-- {/* Platform */}<div>- <div className="text-xs font-semibold uppercase tracking-wider text-gray-400 dark:text-zinc-500 mb-2 px-1">Platform</div>- <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">- <ConceptItem href="/developer/core-concepts/stores"- icon={<SmallIcon><path d="m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7" /><path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8" /><path d="M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4" /><rect width="20" height="5" x="2" y="7" /></SmallIcon>}- title="Stores" />- <ConceptItem href="/developer/core-concepts/channels"- icon={<SmallIcon><path d="M4.9 16.1C1 12.2 1 5.8 4.9 1.9" /><path d="M7.8 4.7a6.14 6.14 0 0 0-.8 7.5" /><circle cx="12" cy="9" r="2" /><path d="M16.2 4.8c2 2 2.26 5.11.8 7.47" /><path d="M19.1 1.9a9.96 9.96 0 0 1 0 14.1" /><path d="M9.5 18h5" /><path d="m8 22 4-11 4 11" /></SmallIcon>}- title="Channels" />- <ConceptItem href="/developer/core-concepts/markets"- icon={<SmallIcon><circle cx="12" cy="12" r="10" /><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20" /><path d="M2 12h20" /></SmallIcon>}- title="Markets" />- <ConceptItem href="/developer/core-concepts/customers"- icon={<SmallIcon><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" /><path d="M22 21v-2a4 4 0 0 0-3-3.87" /><path d="M16 3.13a4 4 0 0 1 0 7.75" /></SmallIcon>}- title="Customers" />+ <div className="flex flex-wrap gap-2.5">+ <Pill href="/developer/how-to/build-a-marketplace">How do I build a marketplace?</Pill>+ <Pill href="/developer/how-to/build-a-b2b-store">How do I sell B2B?</Pill>+ <Pill href="/developer/how-to/sell-digital-products">How do I sell digital products?</Pill>+ <Pill href="/developer/how-to/custom-payment-method">How do I add a payment method?</Pill>+ <Pill href="/developer/core-concepts/metafields">How do I add custom fields?</Pill>+ <Pill href="/developer/how-to/custom-promotion">How do I build a promotion?</Pill>+ <Pill href="/developer/customization/api">How do I extend the API?</Pill>+ <Pill href="/developer/dashboard/plugins/overview">How do I write a dashboard plugin?</Pill>+ <Pill href="/developer/how-to/custom-search-provider">How do I plug in search?</Pill></div>- </div>-- {/* Extensibility */}- <div>- <div className="text-xs font-semibold uppercase tracking-wider text-gray-400 dark:text-zinc-500 mb-2 px-1">Extensibility</div>- <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">- <ConceptItem href="/developer/core-concepts/events"- icon={<SmallIcon><path d="m13 2-2 2.5h3L12 7" /><path d="M10 14v-3" /><path d="M14 14v-3" /><path d="M11 19c-1.7 0-3-1.3-3-3v-2h8v2c0 1.7-1.3 3-3 3Z" /><path d="M12 22v-3" /></SmallIcon>}- title="Events" />- <ConceptItem href="/developer/core-concepts/webhooks"- icon={<SmallIcon><path d="M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2" /><path d="m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06" /><path d="m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 .8 7.92" /></SmallIcon>}- title="Webhooks" />- <ConceptItem href="/developer/core-concepts/translations"- icon={<SmallIcon><path d="m5 8 6 6" /><path d="m4 14 6-6 2-3" /><path d="M2 5h12" /><path d="M7 2h1" /><path d="m22 22-5-10-5 10" /><path d="M14 18h6" /></SmallIcon>}- title="Translations" />- <ConceptItem href="/developer/core-concepts/metafields"- icon={<SmallIcon><path d="M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" /><path d="M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z" /></SmallIcon>}- title="Metafields" />+ <div className="mt-8 pt-6 border-t border-[#e9e5dd]/80 dark:border-[#3f3e3c] flex flex-wrap items-center gap-2.5">+ <span className="font-mono text-xs uppercase tracking-[0.14em] text-[#999999] dark:text-zinc-500 mr-1">Reference</span>+ <Pill href="/api-reference/store-api/introduction">Store API</Pill>+ <Pill href="/api-reference/admin-api/introduction">Admin API</Pill>+ <Pill href="/developer/sdk/quickstart">TypeScript SDK</Pill>+ <Pill href="/developer/cli/quickstart">CLI</Pill></div></div>-</div>- </div>-- {/* ── SECTION 3: USE CASES ── */}- <div className="mb-16">- <SectionHeading title="Solutions & Use Cases" description="See how teams use Spree for different commerce models" />- <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">- <UseCaseCard href="/use-case/multi-store/model"- icon={<SmallIcon><path d="m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7" /><path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8" /><path d="M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4" /><rect width="20" height="5" x="2" y="7" /></SmallIcon>}- title="Multi-Store"- description="Run multiple storefronts from one backend with shared catalog, inventory, and orders." />- <UseCaseCard href="/use-case/marketplace/model"- icon={<SmallIcon><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" /><path d="M22 21v-2a4 4 0 0 0-3-3.87" /><path d="M16 3.13a4 4 0 0 1 0 7.75" /></SmallIcon>}- title="Marketplace"- description="Multi-vendor marketplace with vendor dashboards, split payments, and per-vendor fulfillment." />- <UseCaseCard href="/use-case/b2b/b2b-commerce-model"- icon={<SmallIcon><path d="M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z" /><path d="M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2" /><path d="M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2" /><path d="M10 6h4" /><path d="M10 10h4" /><path d="M10 14h4" /><path d="M10 18h4" /></SmallIcon>}- title="B2B Commerce"- description="Wholesale pricing, company accounts, purchase orders, and buyer-specific catalogs." />- <UseCaseCard href="/use-case/multi-tenant/multi-tenant-model"- icon={<SmallIcon><rect width="7" height="7" x="14" y="3" rx="1" /><path d="M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3" /></SmallIcon>}- title="Multi-Tenant"- description="White-label SaaS, franchise networks, and multi-brand enterprise from a single deployment." />- <UseCaseCard href="/use-case/digital-products/model"- icon={<SmallIcon><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" /><path d="M14 2v4a2 2 0 0 0 2 2h4" /><path d="M10 18v-1" /><path d="M14 18v-1" /><path d="M10 12v-1" /><path d="M14 12v-1" /></SmallIcon>}- title="Digital Products"- description="Downloadable goods, licenses, and digital subscriptions with fulfillment automation." />- <UseCaseCard href="/use-case/chatgpt-integration/chatgpt-shopping"- icon={<SmallIcon><path d="M12 8V4H8" /><rect width="16" height="12" x="4" y="8" rx="2" /><path d="M2 14h2" /><path d="M20 14h2" /><path d="M15 13v2" /><path d="M9 13v2" /></SmallIcon>}- title="ChatGPT Shopping"- description="AI-powered shopping experience with instant checkout via ChatGPT integration." />- </div>- </div>-- {/* ── SECTION 4: SDK & INTEGRATIONS ── */}- <div className="mb-16">- <div className="grid sm:grid-cols-2 gap-8">+ </Section>- {/* SDK & Tools */}+ {/* AI AGENTS */}+ <Section className="home-band">+ <div className="grid lg:grid-cols-[1fr_1.15fr] gap-12 lg:gap-16 items-start"><div>- <SectionHeading title="SDK & Tools" description="TypeScript-first developer experience" />- <div className="space-y-2">- <ResourceLink href="/developer/sdk/quickstart"- icon={<SmallIcon><polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" /></SmallIcon>}- title="@spree/sdk"- description="TypeScript SDK for Store and Admin APIs" />- <ResourceLink href="/developer/create-spree-app/quickstart"- icon={<SmallIcon><path d="M5 12h14" /><path d="M12 5v14" /></SmallIcon>}- title="create-spree-app"- description="Scaffold a new Spree project in seconds" />- <ResourceLink href="/developer/cli/quickstart"- icon={<SmallIcon><polyline points="4 17 10 11 4 5" /><line x1="12" x2="20" y1="19" y2="19" /></SmallIcon>}- title="Spree CLI"- description="Command-line tools for development" />- <ResourceLink href="/developer/agentic/overview"- icon={<SmallIcon><path d="M12 8V4H8" /><rect width="16" height="12" x="4" y="8" rx="2" /><path d="M2 14h2" /><path d="M20 14h2" /><path d="M15 13v2" /><path d="M9 13v2" /></SmallIcon>}- title="Agentic Development"- description="Agent skills, docs MCP server, LLM-ready docs" />- <ResourceLink href="/api-reference"- icon={<SmallIcon><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4" /><path d="M3 5v14a2 2 0 0 0 2 2h16v-5" /><path d="M18 12a2 2 0 0 0 0 4h4v-4z" /></SmallIcon>}- title="API Reference"- description="OpenAPI spec with interactive explorer" />- </div>+ <Eyebrow>For AI agents</Eyebrow>+ <SectionTitle>Give your AI tools the full picture</SectionTitle>+ <Lede>+ Connect your coding assistant to the Spree docs over MCP, or install the agent skills so it+ knows Spree's conventions before it writes a line of code.+ </Lede>+ <a href="/developer/agentic/overview"+ className="mt-6 inline-flex items-center gap-2 text-sm font-medium text-blue-600 dark:text-blue-400 no-underline hover:gap-3 transition-all">+ Set up AI-assisted development+ <Icon className="w-4 h-4"><path d="M5 12h14" /><path d="m12 5 7 7-7 7" /></Icon>+ </a></div>-- {/* Integrations */}- <div>- <SectionHeading title="Integrations" description="Pre-built connectors for popular services" />- <div className="grid grid-cols-4 gap-1">- <IntegrationItem href="/integrations/payments/stripe" name="Stripe"- icon={<SmallIcon><rect width="20" height="14" x="2" y="5" rx="2" /><line x1="2" x2="22" y1="10" y2="10" /></SmallIcon>} />- <IntegrationItem href="/integrations/payments/paypal" name="PayPal"- icon={<SmallIcon><circle cx="12" cy="12" r="10" /><line x1="12" x2="12" y1="8" y2="16" /><line x1="8" x2="16" y1="12" y2="12" /></SmallIcon>} />- <IntegrationItem href="/integrations/payments/adyen" name="Adyen"- icon={<SmallIcon><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4" /><path d="M3 5v14a2 2 0 0 0 2 2h16v-5" /><path d="M18 12a2 2 0 0 0 0 4h4v-4z" /></SmallIcon>} />- <IntegrationItem href="/integrations/payments/razorpay" name="Razorpay"- icon={<SmallIcon><path d="m13 2-2 2.5h3L12 7" /><path d="M12 22V7" /></SmallIcon>} />- <IntegrationItem href="/integrations/analytics/google-analytics" name="GA4"- icon={<SmallIcon><path d="M3 3v16a2 2 0 0 0 2 2h16" /><path d="m19 9-5 5-4-4-3 3" /></SmallIcon>} />- <IntegrationItem href="/integrations/analytics/google-tag-manager" name="GTM"- icon={<SmallIcon><path d="M9.568 3H5.25A2.25 2.25 0 0 0 3 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 0 0 5.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 0 0 9.568 3Z" /><path d="M6 6h.01" /></SmallIcon>} />- <IntegrationItem href="/integrations/marketing/klaviyo" name="Klaviyo"- icon={<SmallIcon><rect width="20" height="16" x="2" y="4" rx="2" /><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" /></SmallIcon>} />- <IntegrationItem href="/integrations" name="All"- icon={<SmallIcon><path d="M5 12h14" /><path d="M12 5v14" /></SmallIcon>} />- </div>+ <div className="space-y-5">+ <CopyBox label="Install the agent skills" command="npx skills add spree/agent-skills" />+ <CopyBox label="Add the MCP server" command="claude mcp add spree-docs --transport http https://spreecommerce.org/docs/mcp" />+ <p className="text-sm text-[#666666] dark:text-zinc-400 m-0">+ Works with Claude Code, Cursor, VS Code and more. Every page is also served as plain+ markdown — see <a href="/developer/agentic/llm-docs" className="text-blue-600 dark:text-blue-400">LLM-ready docs</a>.+ </p></div>-</div>- </div>-- {/* ── SECTION 5: MORE RESOURCES ── */}- <div className="border-t border-gray-200 dark:border-zinc-800 pt-10">- <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">- <a href="/docs/user" className="group text-center p-4 rounded-lg hover:bg-blue-50 dark:hover:bg-zinc-800/50 transition-colors no-underline">- <div className="text-sm font-medium text-gray-700 dark:text-zinc-300 group-hover:text-blue-700 dark:group-hover:text-zinc-100">Admin Guide</div>- <div className="text-xs text-gray-400 dark:text-zinc-500 mt-1">For store operators</div>- </a>- <a href="/docs/developer/deployment/database" className="group text-center p-4 rounded-lg hover:bg-blue-50 dark:hover:bg-zinc-800/50 transition-colors no-underline">- <div className="text-sm font-medium text-gray-700 dark:text-zinc-300 group-hover:text-blue-700 dark:group-hover:text-zinc-100">Deployment</div>- <div className="text-xs text-gray-400 dark:text-zinc-500 mt-1">Docker, AWS, Render</div>- </a>- <a href="/docs/developer/upgrades/quickstart" className="group text-center p-4 rounded-lg hover:bg-blue-50 dark:hover:bg-zinc-800/50 transition-colors no-underline">- <div className="text-sm font-medium text-gray-700 dark:text-zinc-300 group-hover:text-blue-700 dark:group-hover:text-zinc-100">Upgrade Guides</div>- <div className="text-xs text-gray-400 dark:text-zinc-500 mt-1">Version migration paths</div>- </a>- <a href="/docs/developer/contributing/quickstart" className="group text-center p-4 rounded-lg hover:bg-blue-50 dark:hover:bg-zinc-800/50 transition-colors no-underline">- <div className="text-sm font-medium text-gray-700 dark:text-zinc-300 group-hover:text-blue-700 dark:group-hover:text-zinc-100">Contributing</div>- <div className="text-xs text-gray-400 dark:text-zinc-500 mt-1">Help build Spree</div>- </a>+ </Section>++ {/* COMMUNITY */}+ <Section className="home-band-end">+ <Eyebrow>Community & support</Eyebrow>+ <SectionTitle>Get help when you need it</SectionTitle>+ <div className="mt-10 grid md:grid-cols-3 gap-5">+ <Card href="https://discord.spreecommerce.org"+ icon={<Icon><path d="M7.5 7.5c3-1 6-1 9 0" /><path d="M7 16.5c3 1 7 1 10 0" /><path d="M15.5 17c.64 2 .84 2 2 3 1.5-.5 3-1.5 3.5-2.5.5-2.5-.5-8-2.5-11.5-1-.5-2-1-3-1l-.5 1" /><path d="M8.5 17c-.64 2-.84 2-2 3-1.5-.5-3-1.5-3.5-2.5-.5-2.5.5-8 2.5-11.5 1-.5 2-1 3-1l.5 1" /></Icon>}+ title="Discord community">+ Ask questions and swap solutions with other Spree developers.+ </Card>+ <Card href="https://github.com/spree/spree/discussions"+ icon={<Icon><path d="M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z" /><path d="M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1" /></Icon>}+ title="GitHub Discussions">+ Propose features, discuss ideas and follow the development of the core.+ </Card>+ <Card href="https://spreecommerce.org/contact/"+ icon={<Icon><circle cx="12" cy="12" r="10" /><circle cx="12" cy="12" r="4" /><path d="m4.9 4.9 4.2 4.2" /><path d="m14.9 14.9 4.2 4.2" /><path d="m14.9 9.1 4.2-4.2" /><path d="m4.9 19.1 4.2-4.2" /></Icon>}+ title="Enterprise support">+ Running Spree in production? Talk to us about dedicated support for your team.+ </Card></div>- </div>+ </Section></div>diff --git a/docs/style.css b/docs/style.cssindex f59e2189f6..6701f33ee0 100644--- a/docs/style.css+++ b/docs/style.css@@ -1,19 +1,343 @@+/* ---------------------------------------------------------------------------+ Spree documentation theme.++ Colour tokens are copied from the marketing site's design tokens+ (website/src/styles/global.css), which are generated from the Figma+ variable set. Keep the two in sync — this file is the docs' only styling+ hook, so a token that drifts here shows up as a visible seam between+ spreecommerce.org and spreecommerce.org/docs.+--------------------------------------------------------------------------- */++:root {+ /* Brand */+ --spree-accent: #0077ff;+ --spree-accent-strong: #0060ce;++ /* Sand — the warm surface ramp the marketing site is built on */+ --spree-sand-50: #fcfaf7;+ --spree-sand-100: #f7f5f2;+ --spree-sand-150: #e9e5dd;+ --spree-sand-200: #e2dfd8;++ /* Dark sand — warm darks for inverted surfaces */+ --spree-dark-sand-500: #32302e;+ --spree-dark-sand-600: #272626;+ --spree-dark-sand-700: #1e1c1b;+ --spree-dark-sand-800: #191818;++ /* Neutral ramp for text and borders */+ --spree-neutral-100: #eaeaea;+ --spree-neutral-200: #d5d5d5;+ --spree-neutral-400: #999999;+ --spree-neutral-600: #666666;+ --spree-neutral-700: #4d4d4d;+ --spree-neutral-900: #1a1a1a;++ /* Semantic */+ --spree-ink: #1a1a1a;+ --spree-heading: #061932;+ --spree-ink-muted: #666666;+ --spree-border: #e2dfd8;++ /* Sidebar (dashboard-like): neutral pills, not accent-tinted */+ --spree-sidebar-hover: rgb(0 0 0 / 0.04);+ --spree-sidebar-active: rgb(0 0 0 / 0.06);+ --spree-sidebar-radius: 0.625rem;+ --spree-guide: #d8d4cb;+}++.dark {+ --spree-sidebar-hover: rgb(255 255 255 / 0.06);+ --spree-sidebar-active: rgb(255 255 255 / 0.10);+ --spree-border: #3f3e3c;+ --spree-guide: #3f3e3c;+}++/* --- Surfaces ------------------------------------------------------------ */++html:not(.dark) body {+ background: var(--spree-sand-50);+}++html.dark body {+ background: var(--spree-dark-sand-800);+}++/* Headings pick up the site's navy rather than pure black. */+html:not(.dark) h1,+html:not(.dark) h2,+html:not(.dark) h3,+html:not(.dark) h4 {+ color: var(--spree-heading);+}+.nav-logo {height: 32px;}-html:not(.dark) body {- background: #fcfaf8;+/* --- Sidebar ------------------------------------------------------------- */+/* Mirrors the Spree dashboard:+ - the SECTION carries the grey pill when the open page lives inside it+ - the active child is bold text only, no background+ - children get a background on hover, inset rather than full width+ - a hairline guide runs down the children of the open section+ Mintlify marks the section holding the current page with+ li[data-group-tag][data-active="true"], and the current page itself with+ `bg-primary/10 text-primary` — both are repurposed below. */++/* The top-level wrapper ("Develop" / "Manage") exists only because Mintlify+ needs a non-empty group name to make its children collapsible. It carries no+ meaning for the reader, so its header is hidden while the group still works. */+#sidebar-content .sidebar-group-header {+ display: none;+}++#sidebar-content a,+#sidebar-content button:not([class*="group/search"]) {+ border-radius: var(--spree-sidebar-radius) !important;+ padding-top: 0.3125rem !important;+ padding-bottom: 0.3125rem !important;+}++/* Section rows: the primary level of the tree. Same size as their children,+ but taller and more widely spaced, so the top level reads as navigation+ rather than a list (the rhythm Vendure's sidebar uses). */+#sidebar-content ul.sidebar-group > li > button,+#sidebar-content ul.sidebar-group > li > a {+ font-weight: 500;+ padding-top: 0.5rem !important;+ padding-bottom: 0.5rem !important;+}++/* Breathing room between top-level sections. */+#sidebar-content ul.sidebar-group > li + li {+ margin-top: 0.25rem;+}++/* An open section's children sit closer to it than the next section does. */+#sidebar-content li[data-group-tag] > ul {+ margin-top: 0.125rem;+ margin-bottom: 0.375rem;+}++/* Hover: a soft neutral wash, never the accent. */+#sidebar-content a:hover,+#sidebar-content button:not([class*="group/search"]):hover {+ background-color: var(--spree-sidebar-hover) !important;+}++/* The section containing the current page wears the pill. */+#sidebar-content li[data-group-tag][data-active="true"] > button,+#sidebar-content li[data-group-tag][data-active="true"] > a {+ background-color: var(--spree-sidebar-active) !important;+ color: var(--spree-neutral-900) !important;+ font-weight: 600 !important;+}++.dark #sidebar-content li[data-group-tag][data-active="true"] > button,+.dark #sidebar-content li[data-group-tag][data-active="true"] > a {+ color: #ffffff !important;+}++/* The current page itself: bold text, no fill. Mintlify's accent tint and the+ faux-bold text-shadow it pairs with are both removed. */+#sidebar-content a[class*="bg-primary/10"],+#sidebar-content a[class*="bg-primary-light/10"] {+ background-color: transparent !important;+ color: var(--spree-neutral-900) !important;+ font-weight: 600 !important;+ text-shadow: none !important;+}++.dark #sidebar-content a[class*="bg-primary/10"],+.dark #sidebar-content a[class*="bg-primary-light/10"] {+ color: #ffffff !important;+}++/* ...but it still highlights on hover, like any other child. */+#sidebar-content a[class*="bg-primary/10"]:hover,+#sidebar-content a[class*="bg-primary-light/10"]:hover {+ background-color: var(--spree-sidebar-hover) !important;+}++/* Child rows align with their section's *label*, not its icon: a section row+ is 16px padding + a 16px icon + a 12px gap, so children need 44px to line up.+ Mintlify's default 28px leaves them hanging 16px to the left. The right+ margin keeps the hover pill inset rather than full-bleed. */+#sidebar-content ul:not(.sidebar-group) > li > a,+#sidebar-content ul:not(.sidebar-group) > li > button {+ padding-left: 0.5rem !important;+ margin-left: 2.25rem;+ margin-right: 0.25rem;+ width: calc(100% - 2.5rem) !important;+}++/* Third level: the whole row steps right by one indent, so its own guide line+ clears the parent's instead of sitting on top of it. */+#sidebar-content ul:not(.sidebar-group) ul:not(.sidebar-group) > li > a,+#sidebar-content ul:not(.sidebar-group) ul:not(.sidebar-group) > li > button {+ padding-left: 0.5rem !important;+ margin-left: 3.75rem;+ width: calc(100% - 4rem) !important;+}++/* Guide line down the open section's children, sitting under the section+ icon. The list is a plain <ul> with no border of its own.++ Every open group draws its own, each stepped right by one indent so the+ levels read as a nested tree rather than overlapping into one stroke. */+#sidebar-content li[data-group-tag] > ul {+ position: relative;+}++#sidebar-content li[data-group-tag] > ul::before {+ content: "";+ position: absolute;+ left: 1.75rem;+ top: 0;+ bottom: 0;+ width: 1px;+ background-color: var(--spree-guide);+}++/* A nested group's line steps right by the same indent as its rows. */+#sidebar-content li[data-group-tag] li[data-group-tag] > ul::before {+ left: 3.25rem;+}++/* Section icons are mask-based SVGs tinted with a background utility (the+ chevrons are stroke-based and must not be touched, hence the class match).+ Tie them to the label colour so a row reads as one unit. */+#sidebar-content button svg[class*="bg-gray-"],+#sidebar-content a svg[class*="bg-gray-"] {+ background-color: currentColor !important;+ opacity: 0.6;+}++#sidebar-content button:hover svg[class*="bg-gray-"],+#sidebar-content a:hover svg[class*="bg-gray-"],+#sidebar-content li[data-group-tag][data-active="true"] > button svg[class*="bg-gray-"] {+ opacity: 1;+}++/* The almond theme floats a rounded white panel on the shell; its default+ border is a cool grey against our warm sand, which is what makes the header+ and sidebar look like a different colour from the content. */+#content-container {+ border-color: var(--spree-border) !important;+}++.dark #content-container {+ border-color: #3f3e3c !important;+}++/* --- Content width ------------------------------------------------------- */+/* Mintlify caps the article at max-w-xl (576px) and then pads the wrapper by+ another 48px, so on a wide screen most of the page is empty. Widen the+ measure and reclaim the padding — tables, code blocks and the API reference+ are what benefit. Capped rather than fluid so long prose stays readable. */++@media (min-width: 1024px) {+ /* The <main> pads by 64px on each side, then the inner wrapper adds another+ 48px on the left before the gap to the table of contents. */+ #content-container {+ padding-left: 3rem !important;+ padding-right: 3rem !important;+ }++ #content-container > .flex.flex-row-reverse {+ padding-left: 0 !important;+ column-gap: 2.5rem !important;+ }+}++/* The article itself is capped at max-w-xl (576px); a wider measure is what+ actually gives tables, code blocks and API examples room. */+#content-container .flex.flex-row-reverse > .max-w-xl {+ max-width: 52rem;+}++/* --- Navbar --------------------------------------------------------------- */+/* The header is transparent by default and only picks up a background once the+ page scrolls — on the custom-mode homepage it never does, so the bar floats+ over the content. Give it a solid surface and a hairline at all times. */++/* The almond theme lays a 3% black wash (#almond-background-color) across the+ viewport at -z-10. The header paints its own opaque background above it, so+ it renders lighter than the sidebar, which sits on the washed body — the two+ look like different colours despite computing identically. Drop the wash and+ let the sand body show through everywhere. */+#almond-background-color {+ background-color: transparent !important;}-html:not(.dark) #navbar {- border-bottom: 1px solid #e2dfd8;+#navbar {+ background-color: var(--spree-sand-50);}-html:not(.dark) #navbar div {- background: #f7f5f2;++.dark #navbar {+ background-color: var(--spree-dark-sand-800);+}++/* Only the homepage needs the rule: docs pages already read as separated,+ because the white content panel meets the sand header at its own edge.+ Mintlify marks custom-mode pages on the header itself. */+#navbar.is-custom {+ border-bottom: 1px solid var(--spree-border);+}++.dark #navbar.is-custom {+ border-bottom-color: #3f3e3c;+}++/* Mintlify fades its own backdrop layer in on scroll; with a solid bar behind+ it that would double up, so keep it out of the way. */+#navbar > .absolute.inset-0 {+ display: none;+}++/* --- Homepage bands ------------------------------------------------------- */+/* The homepage alternates white bands on the sand body. These are plain CSS+ classes because utility classes passed through an MDX component prop are NOT+ compiled by Mintlify (literal JSX classes are) — a dark: variant sent that+ way silently produces no CSS. */++.home-band {+ background: #ffffff;+}++.dark .home-band {+ background: var(--spree-dark-sand-700);+}++.home-band-end {+ border-bottom: 1px solid rgb(233 229 221 / 0.8);+}++.dark .home-band-end {+ border-bottom-color: #3f3e3c;+}++/* --- Accents ------------------------------------------------------------- */++/* Body links: blue text, no rule beneath it. Mintlify styles `a.link` as dark+ text with a 1px blue border-bottom, which reads as an underline. */+/* Scoped to the article: the navbar tabs carry the same `.link` class and must+ keep their own colours. */+#content-container .link {+ border-bottom: 0 !important;+ color: var(--spree-accent) !important;+ text-decoration: none !important;+}++#content-container .link:hover {+ color: var(--spree-accent-strong) !important;+}++.dark #content-container .link {+ color: #4d9fff !important;}-html:not(.dark) #search-bar-entry,-html:not(.dark) #assistant-entry {- background: #fff;+.dark #content-container .link:hover {+ color: #7fb8ff !important;}diff --git a/docs/user/returns/returns-processing.mdx b/docs/user/returns/returns-processing.mdxindex 9b3b00d993..c4439ffee0 100644--- a/docs/user/returns/returns-processing.mdx+++ b/docs/user/returns/returns-processing.mdx@@ -1,136 +1,87 @@---title: "Returns Processing"-description: "Learn how to process returns in Spree Commerce."+description: "Learn how to process returns, exchanges, and claims in Spree Commerce."----Spree supports native returns processing, giving you full control over how refunds, exchanges, and restocking are handled directly from the admin dashboard. The workflow is designed to be flexible, with clear steps for managing each stage of the return process.+Spree 6 handles everything that happens after a sale with three records, each covering a different situation:-This guide walks you through the full lifecycle of a return: from authorization, to customer return, to final reimbursement.+- **Return** — the customer sends items back and gets their money back.+- **Exchange** — the customer sends items back and gets different items instead, such as another size or colour.+- **Claim** — something went wrong with the delivery. The item arrived damaged, never arrived, or was the wrong product. You can send a replacement, refund the customer, or both, without asking for the original item back.-## 1) Create a Return Authorization (RA)--Returns are initiated from the order, not from the Returns tab, so navigate to the Orders tab and open the relevant order.--+Each one belongs directly to an order, so opening an order shows you everything that has happened to it.<Note>- Alternatively, find the customer in the Customers tab and access their order from there.+ This replaces the older three-step flow of Return Authorization, Customer Return, and Reimbursement. One record now covers the whole operation from request through to refund.</Note>-Click the three-dot menu in the top-right corner and select **New Return Authorization**.----This will open the Return Authorization form.----Here you’ll see a table of line items from the order. For each item, configure the following:--- **Include in RA**: check the box to include this item in the return-- **Product**: name and variant (read-only)-- **Status**: shipment status (e.g., "shipped", read-only)-- **Charged**: amount originally charged to the customer-- **Return Quantity**: set how many units should be returned (0 if not returning)-- **Pre-tax Refund Amount**: amount to be refunded per item-- **Reimbursement Type**: choose from: Exchange, Store Credit, Credit, Original Payment-- **Exchange for**: if Exchange is selected, choose the replacement variant from the dropdown--Below the table, you’ll see a dynamic refund summary showing the Total Pre-Tax Refund amount (e.g., $35.00).--At the bottom of the form complete the additional fields:--- **Location**: stock location the item should be returned to (required)-- **Reason**: select an RMA reason (required)-- **Memo**: optional internal note--Click **Create** to finalize the Return Authorization.+## Returns-You’ll be redirected back to the order overview, where a Return Authorizations section will now appear under the Shipments section. You can edit the RA at any time.+### 1. Open the return-+Find the order and create a return against it, choosing the items coming back and how many units of each. You can also record the reason for the return, which stock location the goods are returning to, and an internal memo.-The RA will also now be listed in the **Returns → Return Authorizations** tab.+Customers can also open returns themselves from their account, if your storefront offers it. Those arrive with the status **requested**.-+### 2. Approve it-## 2) Create a Customer Return+Approving a return tells the customer it is authorised.-With an RA in place, you're ready to log the return of the physical item.--From the same order overview page, click the three-dot menu again and select **New Customer Return**.----This will open the Customer Return form.----The form lists each item from the order. For each item, configure:--- **Include in return**: check if the item has been returned-- **Product**: name and variant (read-only)-- **SKU**: stock keeping unit (read-only)-- **Pre-tax Amount**: non-zero if part of the RA, 0 if not included (read-only)-- **Exchange for**: variant selected for exchange (if applicable) (read-only)-- **Resellable**: check if the item can be restocked; unchecked items won’t be returned to inventory+<Note>+ Spree does not generate prepaid return labels yet. That arrives with the carrier integrations, which is where the label actually comes from. Until then, most merchants send a label from their carrier's own tools and paste the link into the return's notes.+</Note>-Below the table, select:+### 3. Receive the goods-- **Location**: confirm the stock location the items are being returned to+When the parcel arrives, record what actually turned up. Partial returns are normal, so you enter the quantity received for each line rather than assuming everything the customer said they would send has arrived.-Click **Create** to finalize the Customer Return.+You also mark each line as resellable or not. Resellable items go back into stock automatically at the return's stock location; damaged items do not.-You’ll then be returned to the order overview page again, and a new Customer Returns section will appear above the Return Authorizations section.+### 4. Refund the customer-+Refund the return to either the original payment method or store credit. You can refund the full amount or part of it, and you can refund in more than one step — part to store credit and part back to the card, for example.-The return will also now be visible in the Returns tab and can be edited from either location.+Once the refund goes through, the customer receives an email confirming it.-+<Note>+ A return can be cancelled at any point before the goods are received. Cancelling restocks nothing.+</Note>-## 3) Reimburse the Customer+## Exchanges-Once a customer return has been logged, you can process the refund or exchange.+An exchange follows the same path as a return — open, approve, receive — but instead of refunding the customer at the end, you fulfil the replacement items.-In the Customer Returns section, click the three-dot menu and select **Create Reimbursement**.+When you fulfil an exchange, Spree creates the replacement shipment for the quantities that were actually received, and checks the replacements are in stock first.-+If the replacement items are worth less than what came back, the difference is returned to the customer as store credit or refunded to their original payment method. If the replacements are worth more, Spree records the difference but does not charge the customer automatically — collecting that balance is up to you, so nobody's card is charged without them agreeing to it.-This will create the reimbursement immediately and redirect you to the reimbursement form.+## Claims-+A claim starts when a customer reports a problem. Claims record what went wrong — damaged, missing, wrong item, or another reason you define — and the customer can attach photographs as evidence.-Here you can review the items to be reimbursed, and override the reimbursement type or the exchange variant if necessary (e.g., reimburse with store credits instead of the original payment).+When you resolve a claim you choose what to do:-Click **Reimburse** to finalize the return process:+- **Refund** — money back, with no items required in return.+- **Replacement** — ship the item again, either the same variant or a different one.+- **Refund and replacement** — both.-- If it’s a refund, the customer will be reimbursed via the selected method.-- If it’s an exchange, a new shipment will be created on the order and can be fulfilled like any other shipment.+You can also deny a claim if it does not hold up, or cancel it.-+## Where to find them-### Alternative Method+Returns, exchanges, and claims each have their own section in the dashboard, so you can see everything in progress across all orders. Individual records also appear on the order they belong to, giving you the full history of that order in one place.-If you’d like to review the Customer Return before reimbursing the customer, you can instead select **Edit** from the three-dot menu, or just click on the Customer Return itself.+## Reasons-This will redirect you to a Customer Return summary that includes a Reimbursements section.+Spree keeps two separate lists of reasons, managed under **Settings → Returns & reasons** and seeded when your store is created:-+- **Return reasons** explain why a customer is sending something back — "wrong size", "changed my mind", "no longer needed". These apply to both returns and exchanges.+- **Claim reasons** explain what went wrong on your end — "arrived damaged", "never arrived", "wrong item sent".-This form displays:+They are kept separate because they answer different questions, and mixing them makes reporting less useful. See [Settings → Returns Configuration](/user/settings/returns-configuration) for how to manage them.-- Customer name-- Order number-- Reimbursement status-- Pre-tax total-- Line item details:- - Product- - Amount- - Reimbursement Type- - Exchange For- - Acceptance Errors+## Return policy-At the bottom of the page you’ll find the **Reimbursements** section.+Spree does not enforce a return window, restocking fee, or final-sale rule out of the box. Every merchant's policy differs, and the rules often vary by country for legal reasons.-Simply click **Create Reimbursement** and follow the steps outlined previously.\ No newline at end of file+Instead, your developers can attach your policy to the point where a return is created. A common setup enforces the policy for customers opening returns themselves, while still letting your staff override it — so a supervisor can accept a return outside the window for a good customer without needing a code change.diff --git a/docs/user/settings/returns-configuration.mdx b/docs/user/settings/returns-configuration.mdxindex d68aafb0e2..baf66c879f 100644--- a/docs/user/settings/returns-configuration.mdx+++ b/docs/user/settings/returns-configuration.mdx@@ -1,127 +1,59 @@---title: "Returns Configuration"-description: "Learn how to define return authorization reasons, refund reasons, and reimbursement types."+description: "Learn how to define return reasons, claim reasons, and refund reasons."---Returns management is a crucial part of ecommerce operations. It builds customer trust, streamlines support workflows, and helps maintain clarity around inventory and financial adjustments.-Not all eCommerce platforms offer built-in tools for managing returns, but fortunately Spree does - no extra plugins or custom development needed.+Not all ecommerce platforms offer built-in tools for managing returns, but fortunately Spree does — no extra plugins or custom development needed.-To get started with Returns, navigate to the Returns tab of the Settings menu.+Before you start processing returns, it is worth setting up the three lists of reasons Spree uses. Each answers a different question, which is why they are kept apart: mixing them together makes your reporting far less useful.-+## Return Reasons-Here you’ll notice three subtabs for managing Return Authorization Reasons, Refund Reasons, and Reimbursement Types. Let’s look at each in detail:+Return reasons record why a customer is sending something back. They apply to both returns and exchanges.-## Return Authorization Reasons+Typical examples are "Wrong size", "No longer needed", "Different from description", and "Arrived too late".-+Each reason has two fields:-Return Merchandise Authorizations (RMAs) specify the reasons a customer provides when requesting to return an item. These reasons help categorize returns for internal reporting and customer service workflows.+- **Name**: the reason itself, as your team and customers will see it.+- **Status**: whether the reason is available for use. Setting a reason to inactive hides it from new returns without deleting the history of returns that already used it.-RMAs only have two fields:+## Claim Reasons-- **Name**: The visible reason for the return (e.g., Wrong size, No longer needed).-- **Status**: Toggle whether the reason is available for use in the returns flow. Inactive reasons are hidden but not deleted.+Claim reasons record what went wrong with a delivery — problems on your end rather than a customer changing their mind.-### Add New Return Authorization+Typical examples are "Arrived damaged", "Never arrived", "Wrong item sent", and "Missing item from order".-To add a new return authorization reason, click ‘New RMA Reason’ in the top right corner and you’ll be redirected to the RMA reason creation form.+They have the same two fields as return reasons: a name and a status.---Simply enter the name, set the status, and click Create to save the new RMA reason.--### Edit Return Authorization--To edit an RMA reason, simply click on the RMA’s row in the overview.----The Edit form looks more or less identical to the Create form, but with pre-filled data, and Update buttons rather than Create buttons.--Simply update fields as needed and then click Update to save changes.--### Delete Return Authorization--To delete an RMA reason, simply open the Edit form as shown above and click Delete.+<Note>+ Claims also have a separate **type** field — damaged, missing, wrong item, or other — which is a broader grouping than the reason. Your developers can add more types if the standard four do not fit your business.+</Note>## Refund Reasons---Refund Reasons are used internally to explain why a refund was issued. These help with tracking, reporting, and communication across teams.--Refund reasons also have two fields:--- **Name**: A label for the reason (e.g., Return processing, Order cancelled).-- **Status**: Toggle whether the reason is available for use in the returns flow. Inactive reasons are hidden but not deleted.--### Add New Refund Reason--To add a new refund reason, click ‘New Refund Reason’ in the top right corner and you’ll be redirected to the refund reason creation form.----Simply enter the name, set the status, and click Create to save the new refund reason.--### Edit Refund Reason+Refund reasons explain why money was sent back. They are used internally for tracking, reporting, and communication across teams, and they apply to any refund, whether or not a return was involved.-To edit a refund reason, simply click on its row in the overview.+Typical examples are "Return processing" and "Order cancelled".-+## Managing reasons-The Edit form looks more or less identical to the Create form, but with pre-filled data, and Update buttons rather than Create buttons.+All three lists live together under **Settings → Returns & reasons**. Spree seeds a starting set when your store is created, so returns, claims, and refunds work out of the box, and you can add, rename, deactivate, or delete entries from there.-Simply update fields as needed and then click Update to save changes.+Each reason has two fields: its **name**, and whether it is **available on new records**. Turning that switch off retires a reason — it stops appearing when staff open a new return, claim, or refund, while every record that already used it keeps its explanation.-### Delete Refund Reason+A reason that is already attached to a record cannot be deleted, because the records that used it would lose their explanation. Those reasons are marked **In use**. Deactivate one instead to retire it, and rename it at any time — every record pointing at it follows the new name.-To delete a refund reason, simply open the Edit form as shown above and click Delete.+## What about return windows and restocking fees?-## Reimbursement Types+Spree does not ship with a fixed return window, restocking fee, or final-sale setting. Return policy varies enormously between merchants, and often has to differ by country for legal reasons — the European Union, for example, requires a minimum withdrawal period that many other markets do not.---Reimbursement Types define how refunds are paid back to the customer. These options help determine whether a refund goes back to the original payment method, a store credit, or is handled through an exchange.--Reimbursement types have four fields:--- **Name**: The label for this type (e.g., Store credit, Exchange).-- **Type**: The method of reimbursement:- - Credit- - Original payment (e.g., debit card)- - Exchange- - Store credit-- **Status**: Toggle whether the reason is available for use in the returns flow. Inactive reasons are hidden but not deleted.-- **Mutable**: If set to Yes, the reimbursement type can be changed after it's assigned, otherwise it's locked it in.--### Add New Reimbursement Type--To add a reimbursement type, click ‘New Reimbursement Type’’ in the top right corner and you’ll be redirected to the reimbursement type creation form.----Simply enter the name, set the status, and click Create to save the new reimbursement type.--### Edit Reimbursement Type--To edit a reimbursement type, simply click on its row in the overview.----The Edit form looks more or less identical to the Create form, but with pre-filled data, and Update buttons rather than Create buttons.--Simply update fields as needed and then click Update to save changes.--### Delete Reimbursement Type--To delete a reimbursement type, simply open the Edit form as shown above and click **Delete**.+Rather than guessing, Spree gives your developers a place to attach your own policy when a return is created. A common arrangement enforces the policy for customers opening returns themselves, while letting your staff override it, so a supervisor can accept a late return for a loyal customer without needing any code changes.## Processing Returns-Now that you’ve defined all of your RMA reasons, refund reasons, and reimbursement types, you’ll be ready to process returns in the event that a customer requests them.--To learn how to process returns, please refer to [Returns → Returns Processing](https://spreecommerce.org/docs/user/returns/returns-processing).-+Once your reasons are set up, you are ready to handle returns, exchanges, and claims.+To learn how, see [Returns → Returns Processing](/user/returns/returns-processing).diff --git a/docs/developer/admin/admin.mdx b/docs/v5/developer/admin/admin.mdxsimilarity index 91%rename from docs/developer/admin/admin.mdxrename to docs/v5/developer/admin/admin.mdxindex 0dfec62954..49ed5da081 100644--- a/docs/developer/admin/admin.mdx+++ b/docs/v5/developer/admin/admin.mdx@@ -2,6 +2,7 @@title: Admin DashboardsidebarTitle: Overviewdescription: Customize and extend the Spree Admin Dashboard to manage products, orders, customers, promotions, and store settings for your ecommerce platform.+canonical: "https://spreecommerce.org/docs/v5/developer/admin/admin"---The Spree Admin Dashboard is a full-featured administration interface for managing your e-commerce store.@@ -89,12 +90,12 @@ end```<Info>- Learn more about creating admin sections in the [Admin Dashboard Tutorial](/developer/tutorial/admin).+ Learn more about creating admin sections in the [Admin Dashboard Tutorial](/v5/developer/tutorial/admin).</Info>### Views & Templates-Views use standard Rails ERB templates with Spree's [Form Builder](/developer/admin/form-builder) and [Components](/developer/admin/components):+Views use standard Rails ERB templates with Spree's [Form Builder](/v5/developer/admin/form-builder) and [Components](/v5/developer/admin/components):```erb<%# app/views/spree/admin/brands/_form.html.erb %>@@ -129,7 +130,7 @@ Spree Admin uses [Hotwire](https://hotwire.dev/) (Turbo + Stimulus) for interact```<Info>- Add custom JavaScript using [Stimulus controllers](/developer/admin/custom-javascript).+ Add custom JavaScript using [Stimulus controllers](/v5/developer/admin/custom-javascript).</Info>### Styling@@ -149,7 +150,7 @@ The Admin Dashboard uses [Tailwind CSS v4](https://tailwindcss.com/) for styling```<Info>- Learn how to customize styles in [Custom CSS](/developer/admin/custom-css).+ Learn how to customize styles in [Custom CSS](/v5/developer/admin/custom-css).</Info>## Quick Reference@@ -158,10 +159,10 @@ The Admin Dashboard uses [Tailwind CSS v4](https://tailwindcss.com/) for styling| Tool | Purpose | Documentation ||------|---------|---------------|-| Form Builder | Create consistent forms with validation | [Form Builder](/developer/admin/form-builder) |-| Components | Dropdowns, dialogs, icons, badges, etc. | [Components](/developer/admin/components) |-| Helper Methods | Navigation, links, utilities | [Helper Methods](/developer/admin/helper-methods) |-| UI Extensions | Inject content into existing pages | [Extending UI](/developer/admin/extending-ui) |+| Form Builder | Create consistent forms with validation | [Form Builder](/v5/developer/admin/form-builder) |+| Components | Dropdowns, dialogs, icons, badges, etc. | [Components](/v5/developer/admin/components) |+| Helper Methods | Navigation, links, utilities | [Helper Methods](/v5/developer/admin/helper-methods) |+| UI Extensions | Inject content into existing pages | [Extending UI](/v5/developer/admin/extending-ui) |### Common Tasks@@ -206,7 +207,7 @@ Admin users must be authenticated to access the dashboard. Spree supports:- SSO integration<Info>- See [Authentication](/developer/admin/authentication) for setup details.+ See [Authentication](/v5/developer/admin/authentication) for setup details.</Info>### Authorization@@ -224,7 +225,7 @@ authorize! :update, @product```<Info>- See [Permissions](/developer/customization/permissions) for defining custom abilities.+ See [Permissions](/v5/developer/customization/permissions) for defining custom abilities.</Info>## Next Stepsdiff --git a/docs/developer/admin/authentication.mdx b/docs/v5/developer/admin/authentication.mdxsimilarity index 95%rename from docs/developer/admin/authentication.mdxrename to docs/v5/developer/admin/authentication.mdxindex da3f518cb1..e27f82f9a5 100644--- a/docs/developer/admin/authentication.mdx+++ b/docs/v5/developer/admin/authentication.mdx@@ -2,6 +2,7 @@title: Admin Panel AuthenticationsidebarTitle: Authenticationdescription: How to customize the Spree admin panel authentication+canonical: "https://spreecommerce.org/docs/v5/developer/admin/authentication"---Spree allows you to use a different model for the admin panel than the storefront (that's the default since Spree 5.2).diff --git a/docs/developer/admin/components.mdx b/docs/v5/developer/admin/components.mdxsimilarity index 99%rename from docs/developer/admin/components.mdxrename to docs/v5/developer/admin/components.mdxindex d5f634c67b..6929e4278e 100644--- a/docs/developer/admin/components.mdx+++ b/docs/v5/developer/admin/components.mdx@@ -1,6 +1,7 @@---title: Admin ComponentssidebarTitle: Components+canonical: "https://spreecommerce.org/docs/v5/developer/admin/components"---Spree Admin provides a set of reusable UI components that you can use in your custom admin views. These components are implemented as view helpers and integrate with Stimulus controllers for interactivity.@@ -401,7 +402,7 @@ Displays optimized images with automatic WebP conversion and retina support.```<Info>- For comprehensive documentation on image handling, storage configuration, and best practices, see the [Media](/developer/core-concepts/media) guide.+ For comprehensive documentation on image handling, storage configuration, and best practices, see the [Media](/v5/developer/core-concepts/media) guide.</Info>## Tooltipdiff --git a/docs/developer/admin/custom-css.mdx b/docs/v5/developer/admin/custom-css.mdxsimilarity index 98%rename from docs/developer/admin/custom-css.mdxrename to docs/v5/developer/admin/custom-css.mdxindex f253eae6e1..e7d5935557 100644--- a/docs/developer/admin/custom-css.mdx+++ b/docs/v5/developer/admin/custom-css.mdx@@ -2,6 +2,7 @@title: Admin Dashboard Custom CSSsidebarTitle: Custom CSSdescription: Customize the Spree Admin Dashboard with your own CSS by overriding Tailwind variables, adding custom styles, and extending admin views and helpers.+canonical: "https://spreecommerce.org/docs/v5/developer/admin/custom-css"---Spree Admin Dashboard uses [Tailwind CSS v4](https://tailwindcss.com/) for styling. The stylesheet system is designed to be easily customizable while maintaining consistency with the Spree design system.diff --git a/docs/developer/admin/custom-javascript.mdx b/docs/v5/developer/admin/custom-javascript.mdxsimilarity index 98%rename from docs/developer/admin/custom-javascript.mdxrename to docs/v5/developer/admin/custom-javascript.mdxindex c089d97159..f9785de020 100644--- a/docs/developer/admin/custom-javascript.mdx+++ b/docs/v5/developer/admin/custom-javascript.mdx@@ -2,6 +2,7 @@title: Custom JavaScript for Admin DashboardsidebarTitle: Custom JavaScriptdescription: Learn how to add custom JavaScript to your Spree Admin Dashboard+canonical: "https://spreecommerce.org/docs/v5/developer/admin/custom-javascript"---## Extending Admin Dashboard with JavaScriptdiff --git a/docs/developer/admin/extending-ui.mdx b/docs/v5/developer/admin/extending-ui.mdxsimilarity index 94%rename from docs/developer/admin/extending-ui.mdxrename to docs/v5/developer/admin/extending-ui.mdxindex a2a8923049..49b7452059 100644--- a/docs/developer/admin/extending-ui.mdx+++ b/docs/v5/developer/admin/extending-ui.mdx@@ -2,6 +2,7 @@title: Extending Admin Dashboard UIsidebarTitle: Extending UIdescription: Inject custom partials into Spree Admin Dashboard pages using injection points to add fields, buttons, and sections without modifying core code.+canonical: "https://spreecommerce.org/docs/v5/developer/admin/extending-ui"---Spree Admin Dashboard allows you to easily extend existing pages and screens with your own code, without any need to modify the core codebase. This allows you to easily inject your custom UI elements without compromising the integrity of the core codebase. Which in effect allows you to safely update your Spree installation to the latest version.@@ -232,7 +233,7 @@ Here's a list of all places you can inject your custom code:#### Variables<ParamField path="f" type="Spree::Admin::FormBuilder">- The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.+ The [Spree::Admin::FormBuilder](/v5/developer/admin/form-builder) object.</ParamField>Injects code into the orders list filters, to add custom filters.@@ -243,7 +244,7 @@ Here's a list of all places you can inject your custom code:```<Tip>- * `q_number_cont` - The name of the filter field. For filtering we're using [ransack](/developer/core-concepts/search-filtering) gem, so the name of the filter field is the name of the attribute we're filtering by.+ * `q_number_cont` - The name of the filter field. For filtering we're using [ransack](/v5/developer/core-concepts/search-filtering) gem, so the name of the filter field is the name of the attribute we're filtering by.* `data: { filters_target: :input }` - Needed for the [Stimulus Filters controller](https://github.com/spree/spree/blob/main/admin/app/javascript/spree/admin/controllers/filters_controller.js) to work.</Tip></Accordion>@@ -411,7 +412,7 @@ Here's a list of all places you can inject your custom code:#### Variables<ParamField path="f" type="ActionView::Helpers::FormBuilder">- The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.+ The [Spree::Admin::FormBuilder](/v5/developer/admin/form-builder) object.</ParamField>Injects code into the customers list filters. This partial has access to the `f` variable, which is the form builder for the filters.@@ -421,7 +422,7 @@ Here's a list of all places you can inject your custom code:```<Tip>- * Use [ransack](/developer/core-concepts/search-filtering) search syntax for filter field names+ * Use [ransack](/v5/developer/core-concepts/search-filtering) search syntax for filter field names* Include `data: { filters_target: :input }` for proper integration with the Stimulus Filters controller</Tip></Accordion>@@ -481,7 +482,7 @@ Here's a list of all places you can inject your custom code:#### Variables<ParamField path="f" type="Spree::Admin::FormBuilder">- The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.+ The [Spree::Admin::FormBuilder](/v5/developer/admin/form-builder) object.</ParamField>Injects code into the stock items list filters.@@ -493,7 +494,7 @@ Here's a list of all places you can inject your custom code:```<Tip>- Use [ransack](/developer/core-concepts/search-filtering) search syntax for filter field names (e.g., `_lt` for "less than").+ Use [ransack](/v5/developer/core-concepts/search-filtering) search syntax for filter field names (e.g., `_lt` for "less than").</Tip></Accordion></AccordionGroup>@@ -607,7 +608,7 @@ Here's a list of all places you can inject your custom code:#### Variables<ParamField path="f" type="Spree::Admin::FormBuilder">- The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.+ The [Spree::Admin::FormBuilder](/v5/developer/admin/form-builder) object.</ParamField>Injects code into the customer returns list filters.@@ -620,7 +621,7 @@ Here's a list of all places you can inject your custom code:```<Tip>- Use [ransack](/developer/core-concepts/search-filtering) search syntax for filter field names (e.g., `_eq` for "equals").+ Use [ransack](/v5/developer/core-concepts/search-filtering) search syntax for filter field names (e.g., `_eq` for "equals").</Tip></Accordion></AccordionGroup>@@ -708,7 +709,7 @@ Here's a list of all places you can inject your custom code:#### Variables<ParamField path="f" type="Spree::Admin::FormBuilder">- The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.+ The [Spree::Admin::FormBuilder](/v5/developer/admin/form-builder) object.</ParamField>Injects code into the gift cards list filters.@@ -721,7 +722,7 @@ Here's a list of all places you can inject your custom code:```<Tip>- Use [ransack](/developer/core-concepts/search-filtering) search syntax for filter field names (e.g., `_gt` for "greater than").+ Use [ransack](/v5/developer/core-concepts/search-filtering) search syntax for filter field names (e.g., `_gt` for "greater than").</Tip></Accordion></AccordionGroup>@@ -887,7 +888,7 @@ Here's a list of all places you can inject your custom code:#### Variables<ParamField path="f" type="Spree::Admin::FormBuilder">- The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.+ The [Spree::Admin::FormBuilder](/v5/developer/admin/form-builder) object.</ParamField>Injects code into the promotions list filters.@@ -900,7 +901,7 @@ Here's a list of all places you can inject your custom code:```<Tip>- Use [ransack](/developer/core-concepts/search-filtering) search syntax for filter field names.+ Use [ransack](/v5/developer/core-concepts/search-filtering) search syntax for filter field names.</Tip></Accordion></AccordionGroup>@@ -1196,7 +1197,7 @@ Here's a list of all places you can inject your custom code:#### Variables<ParamField path="f" type="Spree::Admin::FormBuilder">- The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.+ The [Spree::Admin::FormBuilder](/v5/developer/admin/form-builder) object.</ParamField>Injects code into the stock transfers list filters.@@ -1209,7 +1210,7 @@ Here's a list of all places you can inject your custom code:```<Tip>- Use [ransack](/developer/core-concepts/search-filtering) search syntax for filter field names.+ Use [ransack](/v5/developer/core-concepts/search-filtering) search syntax for filter field names.</Tip></Accordion></AccordionGroup>@@ -1431,7 +1432,7 @@ Here's a list of all places you can inject your custom code:#### Variables<ParamField path="f" type="Spree::Admin::FormBuilder">- The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.+ The [Spree::Admin::FormBuilder](/v5/developer/admin/form-builder) object.</ParamField>Injects code into the products list filters. This partial has access to the `f` variable, which is the form builder for the filters.@@ -1443,7 +1444,7 @@ Here's a list of all places you can inject your custom code:```<Tip>- * `q_name_cont` is the name of the filter field. For filtering we're using [ransack](/developer/core-concepts/search-filtering) gem, so the name of the filter field is the name of the attribute we're filtering by.+ * `q_name_cont` is the name of the filter field. For filtering we're using [ransack](/v5/developer/core-concepts/search-filtering) gem, so the name of the filter field is the name of the attribute we're filtering by.* `data: { filters_target: :input }` is needed for the [Stimulus Filters controller](https://github.com/spree/spree/blob/main/admin/app/javascript/spree/admin/controllers/filters_controller.js) to work.</Tip></Accordion>@@ -1478,7 +1479,7 @@ Here's a list of all places you can inject your custom code:#### Variables<ParamField path="f" type="Spree::Admin::FormBuilder">- The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.+ The [Spree::Admin::FormBuilder](/v5/developer/admin/form-builder) object.</ParamField><ParamField path="product" type="Spree::Product">@@ -1534,7 +1535,7 @@ Here's a list of all places you can inject your custom code:#### Variables<ParamField path="f" type="Spree::Admin::FormBuilder">- The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.+ The [Spree::Admin::FormBuilder](/v5/developer/admin/form-builder) object.</ParamField><ParamField path="product" type="Spree::Product">@@ -1589,7 +1590,7 @@ Here's a list of all places you can inject your custom code:#### Variables<ParamField path="f" type="Spree::Admin::FormBuilder">- The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.+ The [Spree::Admin::FormBuilder](/v5/developer/admin/form-builder) object.</ParamField><ParamField path="shipping_method" type="Spree::ShippingMethod">@@ -1626,7 +1627,7 @@ Here's a list of all places you can inject your custom code:#### Variables<ParamField path="f" type="Spree::Admin::FormBuilder">- The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.+ The [Spree::Admin::FormBuilder](/v5/developer/admin/form-builder) object.</ParamField><ParamField path="store" type="Spree::Store">@@ -1652,7 +1653,7 @@ Here's a list of all places you can inject your custom code:## Related Documentation-- [Admin Navigation](/developer/admin/navigation) - Add custom menu items to the admin-- [Admin Tables](/developer/admin/tables) - Customize admin list views-- [Form Builder](/developer/admin/form-builder) - Build admin forms with Spree's form helpers-- [Customization Quickstart](/developer/customization/quickstart) - Overview of all customization options+- [Admin Navigation](/v5/developer/admin/navigation) - Add custom menu items to the admin+- [Admin Tables](/v5/developer/admin/tables) - Customize admin list views+- [Form Builder](/v5/developer/admin/form-builder) - Build admin forms with Spree's form helpers+- [Customization Quickstart](/v5/developer/customization/quickstart) - Overview of all customization optionsdiff --git a/docs/developer/admin/form-builder.mdx b/docs/v5/developer/admin/form-builder.mdxsimilarity index 99%rename from docs/developer/admin/form-builder.mdxrename to docs/v5/developer/admin/form-builder.mdxindex d1ff479105..e356c5ada4 100644--- a/docs/developer/admin/form-builder.mdx+++ b/docs/v5/developer/admin/form-builder.mdx@@ -1,6 +1,7 @@---title: Admin Form Builder APIsidebarTitle: Form Builder+canonical: "https://spreecommerce.org/docs/v5/developer/admin/form-builder"---Spree provides a custom `Spree::Admin::FormBuilder` that extends Rails' standard FormBuilder with additional helper methods designed specifically for the admin interface. This form builder ensures consistent styling, error handling, and behavior across all admin forms.diff --git a/docs/developer/admin/helper-methods.mdx b/docs/v5/developer/admin/helper-methods.mdxsimilarity index 97%rename from docs/developer/admin/helper-methods.mdxrename to docs/v5/developer/admin/helper-methods.mdxindex a337192112..03430c7fe6 100644--- a/docs/developer/admin/helper-methods.mdx+++ b/docs/v5/developer/admin/helper-methods.mdx@@ -1,6 +1,7 @@---title: Admin Dashboard Helper MethodssidebarTitle: Helper Methods+canonical: "https://spreecommerce.org/docs/v5/developer/admin/helper-methods"---import SpreeStore from '/snippets/objects/spree_store.mdx'@@ -9,7 +10,7 @@ import SpreeVendor from '/snippets/objects/spree_vendor.mdx'Helper methods available in the Admin Dashboard for navigation, links, and utility functions.<Info>- For UI components that render HTML elements (Dropdowns, Dialogs, Icons, etc.), see the [Components](/developer/admin/components) documentation.+ For UI components that render HTML elements (Dropdowns, Dialogs, Icons, etc.), see the [Components](/v5/developer/admin/components) documentation.</Info>## Navigation Helpers@@ -421,7 +422,7 @@ Renders all registered partials for an injection point.<%= render_admin_partials(:order_page_sidebar, order: @order) %>```-See [Extending UI](/developer/admin/extending-ui) for more information about injection points.+See [Extending UI](/v5/developer/admin/extending-ui) for more information about injection points.## Preference Helpersdiff --git a/docs/developer/admin/navigation.mdx b/docs/v5/developer/admin/navigation.mdxsimilarity index 97%rename from docs/developer/admin/navigation.mdxrename to docs/v5/developer/admin/navigation.mdxindex af54aa6d39..16b3311c73 100644--- a/docs/developer/admin/navigation.mdx+++ b/docs/v5/developer/admin/navigation.mdx@@ -1,6 +1,7 @@---title: Extending Admin NavigationsidebarTitle: Navigation+canonical: "https://spreecommerce.org/docs/v5/developer/admin/navigation"---Spree Admin Dashboard provides a flexible navigation system that allows you to easily extend the sidebar navigation with your own menu items without modifying the core codebase. This enables safe updates while maintaining your customizations.@@ -824,8 +825,8 @@ Register with:### Related Documentation-- [Extending Admin UI](/developer/admin/extending-ui) - Learn about other UI injection points-- [Admin Tables](/developer/admin/tables) - Customize admin list views-- [Helper Methods](/developer/admin/helper-methods) - Explore other admin helper methods-- [Permissions](/developer/customization/permissions) - Understand the authorization system-- [Customization Quickstart](/developer/customization/quickstart) - Overview of all customization options+- [Extending Admin UI](/v5/developer/admin/extending-ui) - Learn about other UI injection points+- [Admin Tables](/v5/developer/admin/tables) - Customize admin list views+- [Helper Methods](/v5/developer/admin/helper-methods) - Explore other admin helper methods+- [Permissions](/v5/developer/customization/permissions) - Understand the authorization system+- [Customization Quickstart](/v5/developer/customization/quickstart) - Overview of all customization optionsdiff --git a/docs/developer/admin/tables.mdx b/docs/v5/developer/admin/tables.mdxsimilarity index 97%rename from docs/developer/admin/tables.mdxrename to docs/v5/developer/admin/tables.mdxindex 92b3252035..63d61daaf6 100644--- a/docs/developer/admin/tables.mdx+++ b/docs/v5/developer/admin/tables.mdx@@ -2,6 +2,7 @@title: Admin TablessidebarTitle: Tablesdescription: Use the Spree Admin Tables DSL to define columns, sorting, filtering, and bulk actions for resource listings, and extend existing admin tables.+canonical: "https://spreecommerce.org/docs/v5/developer/admin/tables"---Spree Admin provides a flexible table system for displaying resource listings with customizable columns, sorting, filtering, and bulk actions. The Tables DSL allows you to define table configurations for your resources and extend existing ones.@@ -562,7 +563,7 @@ Spree.admin.tables.products## Related Documentation-- [Admin Navigation](/developer/admin/navigation) - Add custom menu items to the admin-- [Extending Admin UI](/developer/admin/extending-ui) - Inject partials into admin pages-- [Search & Filtering](/developer/core-concepts/search-filtering) - Add searchable/filterable fields-- [Customization Quickstart](/developer/customization/quickstart) - Overview of all customization options+- [Admin Navigation](/v5/developer/admin/navigation) - Add custom menu items to the admin+- [Extending Admin UI](/v5/developer/admin/extending-ui) - Inject partials into admin pages+- [Search & Filtering](/v5/developer/core-concepts/search-filtering) - Add searchable/filterable fields+- [Customization Quickstart](/v5/developer/customization/quickstart) - Overview of all customization optionsdiff --git a/docs/developer/advanced/adding_spree_to_rails_app.mdx b/docs/v5/developer/advanced/adding_spree_to_rails_app.mdxsimilarity index 97%rename from docs/developer/advanced/adding_spree_to_rails_app.mdxrename to docs/v5/developer/advanced/adding_spree_to_rails_app.mdxindex 50a9d17b17..671ddd75c1 100644--- a/docs/developer/advanced/adding_spree_to_rails_app.mdx+++ b/docs/v5/developer/advanced/adding_spree_to_rails_app.mdx@@ -1,6 +1,7 @@---title: Adding to an existing Rails appdescription: This guide will show you how to add Spree to an existing Ruby on Rails application.+canonical: "https://spreecommerce.org/docs/v5/developer/advanced/adding_spree_to_rails_app"---<Warning>diff --git a/docs/v5/developer/agentic/agent-skills.mdx b/docs/v5/developer/agentic/agent-skills.mdxnew file mode 100644index 0000000000..6df5123633--- /dev/null+++ b/docs/v5/developer/agentic/agent-skills.mdx@@ -0,0 +1,65 @@+---+title: "Agent Skills"+sidebarTitle: Agent Skills+description: "Teach your AI coding agent Spree's conventions — 25 installable skills, a Spree expert subagent, slash commands, and safety hooks."+canonical: "https://spreecommerce.org/docs/developer/agentic/agent-skills"+---++[spree/agent-skills](https://github.com/spree/agent-skills) is a collection of agent skills for Spree Commerce. Skills are markdown instructions your coding agent loads on demand — they encode Spree's conventions, customization decision trees, API patterns, and upgrade flows, so the agent does things the Spree way instead of improvising from training data.++The skills work with Claude Code, Codex, Cursor, GitHub Copilot, Cline, Aider, Zed, Windsurf, OpenCode, and 60+ other agentic tools.++## Install++Run from your project directory:++```bash+npx skills add spree/agent-skills+```++The [skills CLI](https://github.com/vercel-labs/skills) auto-detects which agent tools you have configured and copies the skill files into each tool's native location.++Useful variants:++```bash+npx skills add spree/agent-skills --list # see what's available without installing+npx skills add spree/agent-skills --skill spree-api-v3 # install a subset+npx skills update # update installed skills later+```++## What's inside++| | |+|---|---|+| **25 skills** | Project conventions, the customization decision tree (subscriber vs decorator vs dependency injection vs generator), the v3 Store + Admin API, the `spree:model` / `spree:api_resource` generators, TypeScript SDKs, upgrades, and domain deep-dives: catalog, checkout, payments, promotions, pricing, shipping, i18n, testing, security, performance, deployment. |+| **`spree-expert` subagent** | A Claude Code agent for multi-step investigations (upgrade audits, checkout-flow debugging, API surface planning). It researches in its own context window and returns a focused report, keeping your main session lean. |+| **2 slash commands** | `/spree:doctor` diagnoses the local dev stack (containers, env, migrations, job queues) and prescribes fixes. `/spree:audit-upgrade [version]` runs a read-only upgrade-readiness audit against your codebase. |+| **2 safety hooks** | Block destructive database commands (`db:drop`, `DROP TABLE spree_*`, mass deletes, force-pushes to main) and warn when an edit introduces a hardcoded secret (Stripe live keys, AWS keys, API tokens). Disable with `SPREE_HOOKS_DISABLE=1`. |++Skills activate automatically based on what you're working on — asking your agent to "add a Brand model with an API" pulls in the resource-generator skill; "why is this promotion not applying" pulls in the promotions skill. There's nothing to invoke manually.++## Claude Code plugin (adds commands + hooks)++The `npx skills add` path installs the skills and the subagent. The slash commands and safety hooks need the Claude Code plugin install — run inside a Claude Code session:++```text+/plugin marketplace add spree/agent-skills+/plugin install spree@spree+```++The plugin delivers everything the skills CLI does **plus** `/spree:doctor`, `/spree:audit-upgrade`, and the two safety hooks. Use one install path or the other — installing both makes the skills collide.++## Works in any Spree project++The skills detect your project flavor before running commands:++- **create-spree-app projects** (Docker, Rails app in `backend/`) — commands route through the [Spree CLI](/v5/developer/cli/quickstart) (`spree migrate`, `spree console`, …).+- **Classic Rails apps** (Spree gems in a plain Rails app, no Docker — typical for apps created before Spree 5.4) — the skills fall back to native commands (`bin/rails`, `bundle exec rake`) from the app root.++## Updating++```bash+npx skills update # skills CLI installs+```++Plugin installs update through Claude Code's plugin system (`/plugin` → check for updates). New Spree releases ship matching skill updates — update the skills when you upgrade Spree so the guidance matches your installed version.diff --git a/docs/v5/developer/agentic/llm-docs.mdx b/docs/v5/developer/agentic/llm-docs.mdxnew file mode 100644index 0000000000..f933e6ce5b--- /dev/null+++ b/docs/v5/developer/agentic/llm-docs.mdx@@ -0,0 +1,58 @@+---+title: "LLM-Ready Documentation"+sidebarTitle: LLM-Ready Docs+description: "Every page of the Spree docs is consumable by LLMs — llms.txt indexes, per-page Markdown, and a local npm package for offline agent reads."+canonical: "https://spreecommerce.org/docs/developer/agentic/llm-docs"+---++Beyond the [MCP server](/v5/developer/agentic/mcp), the Spree documentation is published in formats designed for direct LLM consumption. Use these when you want to feed docs into a prompt, point a custom agent at an index, or give agents fast local file access.++## llms.txt++Following the [llms.txt convention](https://llmstxt.org), two indexes are published:++| URL | Contents |+|---|---|+| [`spreecommerce.org/docs/llms.txt`](https://spreecommerce.org/docs/llms.txt) | An index of every documentation page with links — lets an agent discover and fetch exactly the pages it needs |+| [`spreecommerce.org/docs/llms-full.txt`](https://spreecommerce.org/docs/llms-full.txt) | The entire documentation in one file — for tools that ingest a single context dump |++## Per-page Markdown++Append `.md` to any docs URL to get the raw Markdown for that page — ideal for fetching a single authoritative page into context:++```text+https://spreecommerce.org/docs/developer/cli/quickstart.md+https://spreecommerce.org/docs/developer/core-concepts/orders.md+```++## The `@spree/docs` npm package++The full developer documentation also ships as an npm package, so agents working in your repository can `Read` doc files locally — no network round-trips, works offline, and version-pinned to what you installed:++```bash+npm install --save-dev @spree/docs+```++```text+node_modules/@spree/docs/dist/+├── developer/+│ ├── getting-started/ # setup and quickstarts+│ ├── core-concepts/ # products, orders, payments, inventory, …+│ ├── customization/ # decorators, dependencies, events, …+│ ├── storefront/ # Next.js storefront guides+│ ├── sdk/ # TypeScript SDK docs+│ ├── admin/ # admin customization, form builder, components+│ └── how-to/ # focused guides+└── api-reference/+ └── store.yaml # the full Store API OpenAPI spec+```++Projects scaffolded with [create-spree-app](/v5/developer/create-spree-app/quickstart) install it automatically.++<Note>+ The package tracks the docs published at install time and is versioned independently of your Spree gems — run your package manager's update to refresh it, and prefer the [MCP server](/v5/developer/agentic/mcp) when you need the absolute latest.+</Note>++## Generated agent instructions++`create-spree-app` scaffolds every project with a `CLAUDE.md` that tells coding agents where the local docs live, which CLI commands to use (`spree dev`, `spree migrate`, `spree console`), and the customization patterns to follow — so an agent dropped into a fresh project is productive without any prompting. The scaffold's next-steps also suggest installing the [agent skills](/v5/developer/agentic/agent-skills) for the full experience.diff --git a/docs/v5/developer/agentic/mcp.mdx b/docs/v5/developer/agentic/mcp.mdxnew file mode 100644index 0000000000..7c9d2a43e6--- /dev/null+++ b/docs/v5/developer/agentic/mcp.mdx@@ -0,0 +1,75 @@+---+title: "Docs MCP Server"+sidebarTitle: MCP+description: "Connect Claude, Cursor, or any MCP-compatible AI agent to the Spree docs MCP server to search and read the latest documentation while building."+canonical: "https://spreecommerce.org/docs/developer/agentic/mcp"+---++Spree hosts a [Model Context Protocol](https://modelcontextprotocol.io) server on top of this documentation. Once connected, your agent can search the docs and read full pages on demand — answering questions from the latest published documentation instead of stale training data.++```text+https://spreecommerce.org/docs/mcp+```++The server exposes two tools: full-text **search** across the documentation, and **reading** doc pages as Markdown.++## Setup++<Tabs>+ <Tab title="Claude Code">+ ```bash+ claude mcp add --transport http spree-docs https://spreecommerce.org/docs/mcp+ ```++ Scope it to the project (`--scope project`) to share the connection with your team via `.mcp.json`, or keep the default local scope for just yourself.+ </Tab>+ <Tab title="Claude.ai / Claude Desktop">+ Go to [Settings → Connectors](https://claude.ai/settings/connectors), click **Add custom connector**, and paste the URL:++ ```text+ https://spreecommerce.org/docs/mcp+ ```+ </Tab>+ <Tab title="Cursor">+ Add to `.cursor/mcp.json` in your project (or `~/.cursor/mcp.json` globally):++ ```json+ {+ "mcpServers": {+ "spree-docs": {+ "url": "https://spreecommerce.org/docs/mcp"+ }+ }+ }+ ```+ </Tab>+ <Tab title="VS Code (Copilot)">+ Add to `.vscode/mcp.json` in your project:++ ```json+ {+ "servers": {+ "spree-docs": {+ "type": "http",+ "url": "https://spreecommerce.org/docs/mcp"+ }+ }+ }+ ```+ </Tab>+ <Tab title="Other tools">+ Any MCP client that supports remote servers over streamable HTTP can connect — point it at `https://spreecommerce.org/docs/mcp`. No authentication is required.+ </Tab>+</Tabs>++## When to use MCP vs the other doc channels++| Channel | Best for |+|---|---|+| **MCP server** (this page) | The latest published docs; agents working outside a scaffolded project; questions the installed skills don't cover |+| **[`@spree/docs` npm package](/v5/developer/agentic/llm-docs)** | Fast local reads inside a project — no network round-trip, works offline, pinned to what you installed |+| **[Agent skills](/v5/developer/agentic/agent-skills)** | Conventions and how-to knowledge the agent should apply without searching at all |++<Note>+ In create-spree-app projects the generated `AGENTS.md` and `CLAUDE.md` already points agents at the local `@spree/docs` package first — MCP complements it for anything newer than your installed docs version.+</Note>diff --git a/docs/v5/developer/agentic/overview.mdx b/docs/v5/developer/agentic/overview.mdxnew file mode 100644index 0000000000..09aa65fe7b--- /dev/null+++ b/docs/v5/developer/agentic/overview.mdx@@ -0,0 +1,43 @@+---+title: "Agentic Development"+sidebarTitle: Overview+description: "Build, customize, and upgrade Spree stores with AI coding agents using installable agent skills, a documentation MCP server, and LLM-ready docs."+canonical: "https://spreecommerce.org/docs/developer/agentic/overview"+---++Spree ships first-class tooling for AI-assisted development. Whether you use Claude Code, Cursor, Codex, Copilot, or any other coding agent, your agent can learn Spree's conventions, read the right docs at the right time, and run the project safely.++## Why Spree works well with AI agents++- **Strong conventions** — everything is namespaced under `Spree`, models follow predictable patterns (prefixed IDs, `Spree.base_class`, service objects, events), and the v3 REST API uses simple response/request shapes. Conventions are what agents are best at following.+- **Fully Typed APIs** — both Store API and Admin API have OpenAPI specs and official TypeScript SDKs, so agents can generate code with confidence instead of guessing from training data.+- **Docs designed for machine consumption** — the full documentation is available as [llms.txt, per-page Markdown, and a local npm package](/v5/developer/agentic/llm-docs), so agents read authoritative content instead of guessing from training data.+- **A guided project workflow** — [create-spree-app](/v5/developer/create-spree-app/quickstart) scaffolds projects with a generated `AGENTS.md` and `CLAUDE.md`, local docs, and the [Spree CLI](/v5/developer/cli/quickstart), so an agent can boot, migrate, generate code, and run tests without bespoke setup.++## The toolbox++<CardGroup cols={2}>+ <Card title="Agent Skills" icon="graduation-cap" href="/developer/agentic/agent-skills">+ 25 skills teaching agents Spree's conventions, customization patterns, and upgrade flows — installable into 60+ agent tools, plus a Claude Code plugin with slash commands and safety hooks.+ </Card>+ <Card title="Docs MCP Server" icon="plug" href="/developer/agentic/mcp">+ Connect your agent to the Spree documentation MCP server to search and read the latest docs while building.+ </Card>+ <Card title="LLM-Ready Docs" icon="file-text" href="/developer/agentic/llm-docs">+ llms.txt, per-page Markdown, and the `@spree/docs` npm package for fast local reads.+ </Card>+ <Card title="Spree CLI" icon="square-terminal" href="/developer/cli/quickstart">+ A predictable command surface (`spree dev`, `spree generate`, `spree migrate`) plus `spree api` — call the Admin API directly to inspect and drive the store, with zero-config credentials in local dev. Agents debug and act end-to-end.+ </Card>+</CardGroup>++## A typical agentic workflow++1. **Scaffold** a project with `npx create-spree-app@latest my-store` — it generates a `CLAUDE.md`, installs `@spree/docs` for local reference, and wires up the CLI.+2. **Install the agent skills** with `npx skills add spree/agent-skills` so your agent knows the decision tree for customizations (subscriber vs decorator vs dependency injection vs generator) before it writes a line of code.+3. **Connect the docs MCP server** so questions the skills don't cover get answered from the live documentation.+4. **Let the agent work** — generate an API resource (`spree generate api_resource Brand name:string`), customize checkout, integrate a payment provider, or run an upgrade with `spree upgrade`.++<Tip>+ Skills, local docs, and MCP are complementary: skills encode *how to do things the Spree way*, local docs give *fast authoritative lookups*, and MCP covers *the latest published documentation*. Most teams use all three.+</Tip>diff --git a/docs/v5/developer/cli/admin-api.mdx b/docs/v5/developer/cli/admin-api.mdxnew file mode 100644index 0000000000..9332282a91--- /dev/null+++ b/docs/v5/developer/cli/admin-api.mdx@@ -0,0 +1,180 @@+---+title: "Call the Admin API from the CLI"+sidebarTitle: "Admin API"+description: "Use spree api for generic get/post/patch/delete calls, schema introspection, and zero-config credentials — built for scripts and AI agents."+canonical: "https://spreecommerce.org/docs/developer/cli/admin-api"+---++The `spree api` command group turns the CLI into a first-class Admin API client: generic HTTP verbs against any endpoint, schema introspection without leaving the terminal, and credentials that resolve automatically — from a local dev project to a production store profile. It works against any Spree 5.5+ instance and is designed to be driven by both humans and AI coding agents.++```bash+spree api get /products -q status_eq=active --sort -created_at --limit 10+spree api get /orders/ord_x8k2J9aQ --expand items,payments+spree api post /products -d '{"name":"Classic Tee","prices":[{"currency":"USD","amount":"29.99"}]}'+spree api patch /orders/ord_x8k2J9aQ/cancel+spree api endpoints --resource orders+spree api schema "POST /orders/{id}/refunds"+spree api status+```++## Credentials++Credentials resolve through four layers — first match wins:++| Layer | How |+|---|---|+| Flags | `--base-url` / `--api-key` (and `--profile`, which selects a saved profile explicitly) |+| Environment | `SPREE_API_KEY` (+ `SPREE_BASE_URL`) — the path for CI and agents. `SPREE_BASE_URL` is optional: a bare key defaults to `http://localhost:3000`, so local dev needs only the key. Set it for a remote store. |+| Project | Inside a Spree project with the dev stack running, the CLI mints a **read-only** key on first use and stores it in `.spree/credentials.json` (gitignored) |+| Profile | `~/.config/spree/config.json`, written by `spree auth login` |++Host and key resolve **together** per source — a saved or minted key is never silently re-pointed at a host from a different layer. Only `--base-url` (or `SPREE_BASE_URL` paired with `SPREE_API_KEY`) re-points a key deliberately. So against local dev:++```bash+SPREE_API_KEY=sk_xxx spree api get /products # → http://localhost:3000+```++Zero configuration is needed for local development — the first `spree api get` inside your project just works:++```bash+cd my-store+spree api get /products+# No credentials found — minting a read-only API key via the dev stack...+# Saved to .spree/credentials.json (scopes: read_all)+```++Auto-minted keys carry `read_all` only. Writes always require an explicitly created key:++```bash+spree api-key create --type secret --scopes read_orders,write_products+```++For remote stores, create a secret key in the admin under **Settings → API Keys** and save it as a profile — the key is read from a prompt, never from a flag:++```bash+spree auth login --profile prod --base-url https://store.example.com+spree api get /orders --profile prod -q "status_eq=complete"+spree auth status+spree auth logout --profile prod+```++### Use with a sandbox++A [free sandbox](https://console.spree.sh) works like any remote store. Create a secret key in the sandbox admin under **Settings → API Keys**, then save it as a profile:++```bash+spree auth login --profile sandbox --base-url https://your-store.spree.sh+spree api get /products --profile sandbox+```++No local project or Docker needed — the CLI (`npm install -g @spree/cli`) plus a sandbox is a complete environment for exploring the Admin API.++## Reading data++`-q` takes [Ransack](/api-reference/admin-api/querying) predicates as repeatable `key=value` pairs; sorting, pagination, and shaping flags pass through under the Admin API conventions:++```bash+spree api get /products -q name_cont=shirt -q status_eq=active+spree api get /orders --sort -created_at --page 2 --limit 50+spree api get /products/prod_86Rf07xd --expand variants,variants.prices+spree api get /customers --fields id,email --format table+```++`--fields` trims the response to the attributes you name (comma-separated). The resource `id` is **always returned** even if you don't list it, so you only need to name the extra fields. `--expand` is the companion axis — `--fields` selects top-level attributes, `--expand` pulls in related resources:++```bash+spree api get /products --fields name,price # → id + name + price+spree api get /products --fields name --expand variants+```++### Output format++Output is JSON on stdout, and it adapts to where it goes:++- **In a terminal** — indented and syntax-colored, for reading.+- **Piped or redirected** — compact, single-line, uncolored, so it stays fast and feeds cleanly into `jq` (color codes would corrupt it).++```bash+spree api get /products --limit 5 | jq '.data[].name'+```++`--format table` renders collections as a table for humans (nested objects collapse to `{…}`, arrays to `[N]`).++## Writing data++Request bodies are flat JSON (no root wrapping), inline, from a file, or from stdin:++```bash+spree api post /products -d '{"name":"Classic Tee","prices":[{"currency":"USD","amount":"29.99"}]}'+spree api post /orders/ord_x8k2J9aQ/refunds -d @refund.json+cat prices.json | spree api post /prices/bulk_upsert -d -+spree api delete /products/prod_86Rf07xd+```++Mutations automatically carry an `Idempotency-Key`, so retries are safe.++### Creating products++A product is a catalog grouping; everything purchasable — SKU, price, stock, weight — lives on its variants. For a **simple product** with no options, ship a top-level `prices` array and Spree creates the single backing variant for you:++```bash+spree api post /products -d '{"name":"Classic Tee","prices":[{"currency":"USD","amount":"29.99"}]}'+```++For a product with options, send the `variants` array, each with its own `options` and `prices` (and optionally `stock_items`):++```bash+spree api post /products -d '{+ "name": "Classic Tee",+ "variants": [+ { "sku": "TEE-S", "options": [{"name":"size","value":"Small"}], "prices": [{"currency":"USD","amount":"29.99"}] },+ { "sku": "TEE-M", "options": [{"name":"size","value":"Medium"}], "prices": [{"currency":"USD","amount":"29.99"}] }+ ]+}'+```++Run `spree api schema "POST /products"` for the full request body.++## Discovering endpoints and schemas++The CLI bundles a snapshot of the Admin API OpenAPI spec, so discovery works offline:++```bash+spree api endpoints --resource orders # methods, paths, required scopes+spree api endpoints --search "gift card"+spree api schema "POST /orders" # parameters + request/response schema+spree api status # resolved credentials + server reachability+```++`spree api endpoints` shows the `read_*` / `write_*` scope each endpoint requires (see [Authentication](/api-reference/admin-api/authentication)) — useful for deciding what to grant a new key.++### Shell completion++Tab-completion suggests resource paths, Ransack predicate stems (`name_cont=`, `status_eq=`, …), and scope names — all offline from the bundled spec. Add the generated script to your shell:++```bash+# zsh — add to ~/.zshrc+eval "$(spree completion zsh)"+# bash — add to ~/.bashrc+eval "$(spree completion bash)"+# fish — add to ~/.config/fish/config.fish+spree completion fish | source+```++Then `spree api get /pro⇥` completes to `/products`, and `spree api get /products -q name_⇥` offers the Ransack predicates.++## Errors and exit codes++API errors print the error envelope to stderr and exit `1`; usage and configuration problems exit `2`. A scope denial includes the exact remediation:++```text+access_denied: API key lacks scope: write_products+{+ "details": { "required_scope": "write_products" }+}+Hint: mint a key carrying this scope — spree api-key create --type secret --scopes write_products+```++## Using it with AI agents++Agents with shell access (Claude Code, Cursor, and similar) can drive a Spree back office through `spree api` with no extra configuration: inside a project the credentials self-provision read-only, and for remote stores two environment variables (`SPREE_BASE_URL`, `SPREE_API_KEY`) are the whole contract. The `endpoints`/`schema` commands give agents request shapes on demand instead of loading the entire API surface up front, and error messages name the missing scope so agents can self-correct.diff --git a/docs/v5/developer/cli/quickstart.mdx b/docs/v5/developer/cli/quickstart.mdxnew file mode 100644index 0000000000..0ce1efcfd9--- /dev/null+++ b/docs/v5/developer/cli/quickstart.mdx@@ -0,0 +1,348 @@+---+title: Spree CLI+sidebarTitle: Overview+description: Install and use the @spree/cli to scaffold, run, build, and migrate Spree projects — and call the Admin API directly from the command line.+canonical: "https://spreecommerce.org/docs/developer/cli/quickstart"+---++The Spree CLI (`@spree/cli`) does two things from your terminal:++1. **Manages your Spree project** — boot the Docker stack, run generators and migrations, tail logs, open a console, upgrade versions.+2. **Calls the Admin API** — generic `get`/`post`/`patch`/`delete` commands to read, write, and explore your store's data, with zero-config credentials in local dev. See [Admin API from the CLI](/v5/developer/cli/admin-api).++```bash+spree dev # boot the project+spree api get /orders -q status_eq=complete --limit 10 # query the Admin API+spree api post /products -d '{"name":"Classic Tee","prices":[{"currency":"USD","amount":"29.99"}]}' # create a resource+spree api endpoints --search refund # discover endpoints, offline+```++The `spree api` commands work against any Spree 5.5+ instance and are built for both humans and AI agents — see the dedicated [Admin API from the CLI](/v5/developer/cli/admin-api) guide. The rest of this page covers project management.++## Installation++The CLI is included automatically when you scaffold a project with `create-spree-app`. You can also install it globally:++```bash+npm install -g @spree/cli+```++Then run commands from your project directory:++```bash+spree dev+```++Or use `npx` without installing:++```bash+npx @spree/cli dev+```++## Commands++### `spree init`++First-run setup. Starts Docker services, seeds the database, generates an API key, and optionally loads sample data.++```bash+spree init+spree init --no-sample-data # Skip sample data+spree init --no-open # Skip opening browser+```++### `spree dev`++Run the app in the foreground — streams web + worker logs; `Ctrl+C` stops them. The databases keep running for a fast next boot (`spree stop` shuts everything down).++```bash+spree dev+```++### `spree stop`++Stop all services.++```bash+spree stop+```++### `spree restart`++Restart `web` and `worker` in place — same image, same volumes, fresh Rails process. Good for `config/initializers/*.rb` changes or anything Zeitwerk doesn't auto-reload.++```bash+spree restart+```++Not appropriate for Gemfile changes (use `spree bundle install`, then Ctrl+C and re-run `spree dev`), Dockerfile / `.ruby-version` changes (use `spree build`), or compose file changes (Ctrl+C and re-run `spree dev`).++### `spree update`++Pull the latest Spree Docker image and recreate containers. Migrations run automatically on startup.++```bash+spree update+```++### `spree build`++Rebuild the dev image after Dockerfile or `.ruby-version` changes. Only relevant after `spree eject`.++```bash+spree build+spree build --reset-bundle # Also drop the bundle_cache volume so gems re-seed+spree build --yes # Skip confirmation prompts (for CI)+```++`spree bundle add` does NOT require a rebuild — gems land in the `bundle_cache` volume which survives image rebuilds.++`--reset-bundle` only drops `bundle_cache`. Postgres, Redis, Meilisearch, and storage volumes are preserved.++### `spree upgrade`++Walk a Spree version upgrade end-to-end inside the dev stack. Runs `bundle update`, applies pending migrations, then walks the version-specific data backfills from the upgrade manifest.++```bash+spree upgrade # Detect target, run the full sequence interactively+spree upgrade --plan # Print the plan without executing (DRY_RUN=1)+spree upgrade --to 5.5 # Cap the walk at a specific target version+spree upgrade --step <id> # Re-run a single step idempotently (skips bundle + migrate)+spree upgrade --yes # Skip the per-step prompts+```++Production upgrades only need the third stage — `bundle install` and `db:migrate` happen in your deploy pipeline. The CLI runs all three for local development. See [Upgrades](/developer/upgrades) for the manual production path.++### `spree eject`++Switch from the prebuilt Docker image to building from your local `backend/` directory. This lets you customize the Rails app — add gems, override models, add migrations, etc.++```bash+spree eject+```++After ejecting, the Docker image is built from `backend/Dockerfile`. Edit files in `backend/` and run `spree dev` to rebuild and restart with your changes.++See [Customizing the Backend](/v5/developer/create-spree-app/quickstart#customizing-the-backend) for details on what you can customize.++### `spree logs`++Stream service logs.++```bash+spree logs # Web service (default)+spree logs worker # Worker service+```++### `spree console`++Open a Rails console.++```bash+spree console+```++### `spree shell`++Open an interactive bash shell inside the web container — the system-shell sibling of `spree console` (Rails) and `spree db:console` (psql). If the web container is down, it starts a one-off container against the same volumes instead. For one-off non-interactive commands, use `spree exec`.++```bash+spree shell+spree bash # alias+```++### `spree open`++Open the admin dashboard in the browser.++```bash+spree open+```++### `spree seed`++Seed the database.++```bash+spree seed+```++### `spree sample-data`++Load sample products, categories, and images.++```bash+spree sample-data+```++### `spree user create`++Create an admin user. Prompts for email and password interactively, or pass them as flags:++```bash+spree user create+spree user create --email [email protected] --password secret123+```++### `spree api-key`++Manage Store and Admin API keys. Secret keys carry [scopes](/api-reference/admin-api/authentication) and require at least one.++```bash+spree api-key list # List all keys+spree api-key create # Interactive+spree api-key create --name "Storefront" --type publishable # Store API key+spree api-key create --name "Admin" --type secret --scopes read_all # Admin API key+spree api-key revoke <id> # Revoke a key+```++### `spree api`++Call the Admin API with generic `get`/`post`/`patch`/`delete` commands — zero-config inside a project (a read-only key is minted on first use), env vars or profiles for remote stores. See [Admin API from the CLI](/v5/developer/cli/admin-api) for the full guide.++```bash+spree api get /products -q status_eq=active --limit 10+spree api post /products -d '{"name":"Classic Tee","prices":[{"currency":"USD","amount":"29.99"}]}'+spree api endpoints --resource orders # endpoints + required scopes, offline+spree api schema "POST /orders" # request/response schema, offline+spree api status+```++### `spree auth`++Save Admin API credentials for remote stores as named profiles.++```bash+spree auth login --profile prod --base-url https://store.example.com+spree api get /orders --profile prod+spree auth status+spree auth logout --profile prod+```++## Dev workflow commands++These mirror the Rails commands you'd run if you were running the app directly on your host — but each is routed through `docker compose exec` against the running stack.++### `spree generate`++Run a generator inside the container. Bare generator names are auto-prefixed with `spree:` — `model` runs `spree:model`, `api_resource` runs `spree:api_resource` — so you get the Spree conventions (`Spree::` namespace, `spree_`-prefixed table, prefixed IDs, `null: false`, no FK constraints) by default. Rails built-ins (`migration`, `scaffold`, `mailer`, `job`, …) and any name containing `:` are forwarded as-is.++```bash+spree generate model Brand name:string slug:string:uniq # runs spree:model+spree generate api_resource Brand name:string slug:string:uniq # runs spree:api_resource — model + v3 Store/Admin API+spree generate subscriber OmsOrderSync order.completed # runs spree:subscriber — event subscriber + registration+spree generate migration AddPositionToSpreeBrands position:integer # Rails built-in, forwarded as-is+```++`spree:api_resource` scaffolds the full v3 surface: model, migration, Store + Admin controllers and serializers, factory, controller specs, and routes.++### `spree migrate`++Install pending Spree migrations from gems, then run `db:migrate` — the canonical post-update sequence.++```bash+spree migrate+spree migrate:status # show the migration log (`db:migrate:status`)+spree migrate:rollback STEP=2 # roll back (`db:rollback`)+```++### `spree db:reset`++Drop, recreate, migrate, and seed the database. **Destructive** — wipes everything. Asks for confirmation.++```bash+spree db:reset+spree db:reset --yes # Skip confirmation (for CI)+```++### `spree db:console`++Open a `psql` session against the dev Postgres database (runs inside the `postgres` container).++```bash+spree db:console+```++### `spree routes`++Show Rails routes. All flags pass through to `bin/rails routes`.++```bash+spree routes+spree routes -g products # Filter by pattern+spree routes -c Spree::Api::V3::Store::ProductsController # Filter by controller+spree routes --expanded+```++### `spree rspec`++Run the RSpec test suite inside the web container with `RAILS_ENV=test`, so tests hit the `spree_test` database — never your development data. Everything after `rspec` passes through, so file paths, line numbers, and flags work as usual.++```bash+spree rspec # full suite+spree rspec spec/models/spree/brand_spec.rb # one file+spree rspec spec/models/spree/brand_spec.rb:15 # one example+spree rspec --format documentation+```++Before the first run, create the test database with `spree rails db:test:prepare`. See the [Testing tutorial](/v5/developer/tutorial/testing) for writing specs.++## Running things inside the container++These are passthrough commands — anything after the subcommand reaches the inner Rails/Bundle/Rake invocation as-is. Useful for ad-hoc commands that don't have a dedicated wrapper.++### `spree exec`++Run an arbitrary command inside the `web` container.++```bash+spree exec ls -la+spree exec env+spree exec ruby -v+```++### `spree rails`++Run a `bin/rails` command.++```bash+spree rails c # Console (alias of `spree console`)+spree rails routes -g products # Alias of `spree routes -g products`+spree rails runner "puts Spree::Product.count"+spree rails new_subcommand arg1 arg2+```++### `spree bundle`++Run a `bundle` command. Gems land in the `bundle_cache` volume (no image rebuild needed).++```bash+spree bundle install+spree bundle add stripe+spree bundle update spree_core+spree bundle outdated+```++### `spree rake`++Run a Rake task.++```bash+spree rake -T # List tasks+spree rake spree:upgrade # Run the version-specific data backfills+spree rake spree:upgrade DRY_RUN=1 # Same, plan only+```++### `spree task`++Shortcut for `bin/rails <task>` (Spree-style rake tasks registered as Rails tasks).++```bash+spree task load_sample_data+spree task spree:price_history:seed+spree task spree:price_history:prune+```++## Pair with AI agents++The CLI's predictable command surface is what AI coding agents drive when working on Spree projects. The [Spree agent skills](/v5/developer/agentic/agent-skills) teach agents these commands and conventions, and the Claude Code plugin adds `/spree:doctor` (stack diagnosis) and `/spree:audit-upgrade` (upgrade-readiness audit) on top. See [Agentic Development](/v5/developer/agentic/overview).diff --git a/docs/v5/developer/contributing/creating-an-extension.mdx b/docs/v5/developer/contributing/creating-an-extension.mdxnew file mode 100644index 0000000000..287a3db27b--- /dev/null+++ b/docs/v5/developer/contributing/creating-an-extension.mdx@@ -0,0 +1,268 @@+---+title: Creating a Spree extension+description: Step-by-step guide to building a Spree extension gem — scaffolding, decorators, migrations, assets, and packaging for distribution on GitHub.+canonical: "https://spreecommerce.org/docs/developer/contributing/creating-an-extension"+---++## Overview++Spree Extensions are a way to add new functionality to your Spree store. They are a great way to extend the functionality of Spree and add new features. You can share them with Spree community on Github so anyone can use them, contribute back and share your improvements. For officially supported integrations, see the [Integrations directory](/integrations).++<Info>+ This tutorial uses decorators for extending Spree models. For extensions that need to react to events (sync with external services, send notifications, etc.), consider using [Events subscribers](/v5/developer/core-concepts/events) instead - they're easier to test and maintain. See [Customization Quickstart](/v5/developer/customization/quickstart) for guidance on choosing the right approach.+</Info>++## Getting Started++Let's build a simple extension. Suppose we want the ability to mark certain products as being on sale. We'd like to be able to set a sale price on a product and show products that are on sale on a separate products page. This is a great example of how an extension can be used to build on the solid Spree foundation.++Install the Spree Extension CLI by running:+++```bash+gem install spree_extension+```++Run the following command from a directory of your choice outside of our Spree application:++```bash+spree-extension simple_sales+```++This creates a `spree_simple_sales` directory with several additional files and directories. After generating the extension make sure you change to its directory:++```bash+cd spree_simple_sales+```++## Adding a Sale Price to Variants++The first thing we need to do is create a migration that adds a sale_price column to [variants](/v5/developer/core-concepts/products#variants).++We can do this with the following command:++```bash+bin/rails g migration add_sale_price_to_spree_variants sale_price:decimal+```++Because we are dealing with prices, we need to now edit the generated migration to ensure the correct precision and scale. Edit the file `db/migrate/XXXXXXXXXXX_add_sale_price_to_spree_variants.rb` so that it contains the following:++```ruby+class AddSalePriceToSpreeVariants < ActiveRecord::Migration[7.1]+ def change+ add_column :spree_variants, :sale_price, :decimal, precision: 8, scale: 2+ end+end+```++## Adding Our Extension to the Spree Application++Before we continue development of our extension, let's add it to the Spree application.++Within the `my_store` application directory, add the following line to the bottom of our `Gemfile`:++```ruby+gem 'spree_simple_sales', path: '../spree_simple_sales'+```++You may have to adjust the path somewhat depending on where you created the extension. You want this to be the path relative to the location of the `my_store` application.++Once you have added the gem, it's time to bundle:++```bash+bundle install+```++Finally, let's run the `spree_simple_sales` install generator to copy over the migration we just created. Answer **yes** if prompted to run migrations:++```bash+# context: Your Spree store's app root (i.e. Rails.root); not the extension's root path.+bin/rails g spree_simple_sales:install+```++## Adding a Controller Action to HomeController++Now we need to extend `Spree::HomeController` and add an action that selects "on sale" products.++ Note for the sake of this example that \`Spree::HomeController\` is only included in spree_storefront so you need to make it a dependency on your extensions \*.gemspec file.++Make sure you are in the `spree_simple_sales` root directory and run the following command to create the directory structure for our controller decorator:++```bash+mkdir -p app/controllers/spree_simple_sales+```++Next, create a new file in the directory we just created called `home_controller_decorator.rb` and add the following content to it:++```ruby+module SpreeSimpleSales+ module HomeControllerDecorator+ def sale+ @products = Spree::Product.joins(:variants_including_master).where.not(sale_price: nil).distinct+ end+ end+end++Spree::HomeController.prepend SpreeSimpleSales::HomeControllerDecorator+```++This will select just the products that have a variant with a `sale_price` set.++We also need to add a route to this action in our `config/routes.rb` file. Let's do this now. Update the routes file to contain the following:++```ruby+Spree::Core::Engine.routes.draw do+ get "/sale" => "home#sale"+end+```++## Viewing On Sale Products++### Setting the Sale Price for a Variant++Now that our variants have the attribute `sale_price` available to them, let's update the sample data so we have at least one product that is on sale in our application. We will need to do this in the rails console for the time being, as we have no admin interface to set sale prices for variants. So, in order to do this, first open up the rails console:++```bash+bin/rails c+```++Now, follow the steps I take in selecting a product and updating its master variant to have a sale price. Note, you may not be editing the exact same product as I am, but this is not important. We just need one "on sale" product to display on the sales page.++```ruby+> product = Spree::Product.first+=> #<Spree::Product id: 107377505, name: "Spree Bag", description: "Lorem ipsum dolor sit amet, consectetuer adipiscing...", available_on: "2013-02-13 18:30:16", deleted_at: nil, permalink: "spree-bag", meta_description: nil, meta_keywords: nil, tax_category_id: 25484906, shipping_category_id: nil, count_on_hand: 10, created_at: "2013-02-13 18:30:16", updated_at: "2013-02-13 18:30:16", on_demand: false>++> variant = product.master+=> #<Spree::Variant id: 833839126, sku: "SPR-00012", weight: nil, height: nil, width: nil, depth: nil, deleted_at: nil, is_master: true, product_id: 107377505, count_on_hand: 10, cost_price: #<BigDecimal:7f8dda5eebf0,'0.21E2',9(36)>, position: nil, lock_version: 0, on_demand: false, cost_currency: nil, sale_price: nil>++> variant.sale_price = 8.00+=> 8.0++> variant.save+=> true+```++## Decorating Variants++Let's fix our extension so that it uses the `sale_price` when it is present.++Next, create the file `app/models/spree_simple_sales/variant_decorator.rb` and add the following content to it:++```ruby+module SpreeSimpleSales+ module VariantDecorator+ def price_in(currency)+ return super unless sale_price.present?+ Spree::Price.new(variant_id: self.id, amount: self.sale_price, currency: currency)+ end+ end+end++Spree::Variant.prepend SpreeSimpleSales::VariantDecorator+```++If there is a `sale_price` present on the product's master variant, we return that price. Otherwise, we call the original implementation of `price_in` using `return super`.++## Testing Our Decorator++It's always a good idea to test your code. We should be extra careful to write tests for our Variant decorator since we are modifying core Spree functionality. Let's write a couple of simple unit tests for `variant_decorator.rb`++### Generating the Test App++An extension is not a full Rails application, so we need something to test our extension against. By running the Spree `test_app` rake task, we can generate a barebones Spree application within our `spec` directory to run our tests against.++We can do this with the following command from the root directory of our extension:++```bash+bundle exec rake test_app+```++After this command completes, you should be able to run `rspec` and see the following output:++```bash+No examples found.++Finished in 0.00005 seconds+0 examples, 0 failures+```++Great! We're ready to start adding some tests. Let's replicate the extension's directory structure in our spec directory by running the following command++```bash+mkdir -p spec/models/spree+```++Now, let's create a new file in this directory called `variant_decorator_spec.rb` and add the following tests to it:++```ruby+require 'spec_helper'++describe Spree::Variant do+ describe "#price_in" do+ it "returns the sale price if it is present" do+ variant = create(:variant, sale_price: 8.00)+ expected = Spree::Price.new(variant_id: variant.id, currency: "USD", amount: variant.sale_price)++ result = variant.price_in("USD")++ expect(result.variant_id).to eq(expected.variant_id)+ expect(result.amount.to_f).to eq(expected.amount.to_f)+ expect(result.currency).to eq(expected.currency)+ end++ it "returns the normal price if it is not on sale" do+ variant = create(:variant, price: 15.00)+ expected = Spree::Price.new(variant_id: variant.id, currency: "USD", amount: variant.price)++ result = variant.price_in("USD")++ expect(result.variant_id).to eq(expected.variant_id)+ expect(result.amount.to_f).to eq(expected.amount.to_f)+ expect(result.currency).to eq(expected.currency)+ end+ end+end+```++These specs test that the `price_in` method we overrode in our `VariantDecorator` returns the correct price both when the sale price is present and when it is not.++## Summary++In this tutorial, you learned how to both install extensions and create your own. A lot of core Spree development concepts were covered and you gained exposure to some of the Spree internals.++## Alternative Approaches++While this tutorial uses decorators to extend Spree's core behavior, modern Spree provides additional patterns that may be more appropriate depending on your use case:++| Use Case | Recommended Approach |+|----------|---------------------|+| Structural changes (associations, validations) | Decorators (as shown in this tutorial) |+| React to model changes | [Events subscribers](/v5/developer/core-concepts/events) |+| External service integration | [Webhooks](/v5/developer/core-concepts/webhooks) |+| Replace core services | [Dependencies injection](/v5/developer/customization/dependencies) |+| Add admin UI elements | [Admin Partials](/v5/developer/admin/extending-ui) |+| Add admin menu items | [Admin Navigation](/v5/developer/admin/navigation) |++For example, if your extension needs to sync data with an external service when products are updated, use an Events subscriber instead of a decorator callback:++```ruby app/subscribers/my_extension/product_sync_subscriber.rb+module MyExtension+ class ProductSyncSubscriber < Spree::Subscriber+ subscribes_to 'product.updated'++ def handle(event)+ product = Spree::Product.find_by_prefix_id(event.payload['id'])+ return unless product++ ExternalService.sync(product)+ end+ end+end+```++## Related Documentation++- [Events](/v5/developer/core-concepts/events) - Subscribe to Spree events+- [Webhooks](/v5/developer/core-concepts/webhooks) - HTTP callbacks for external integrations+- [Dependencies](/v5/developer/customization/dependencies) - Replace core services+- [Customization Quickstart](/v5/developer/customization/quickstart) - Choose the right approachdiff --git a/docs/v5/developer/contributing/developing-spree.mdx b/docs/v5/developer/contributing/developing-spree.mdxnew file mode 100644index 0000000000..951dc47a53--- /dev/null+++ b/docs/v5/developer/contributing/developing-spree.mdx@@ -0,0 +1,448 @@+---+title: Developing Spree+description: Set up a Spree Commerce development environment with Docker, run the RSpec test suite, follow coding conventions, and submit pull requests upstream.+canonical: "https://spreecommerce.org/docs/developer/contributing/developing-spree"+---++Please read our [Code of Conduct](https://github.com/spree/spree/blob/main/CODE_OF_CONDUCT.md) before contributing.++## Cloning the repository++Spree is a big monorepo. For a faster clone, use a **partial clone** which downloads file contents on demand while keeping full commit history for `git log` and `git blame`:++```bash+git clone --filter=blob:none https://github.com/spree/spree.git+```++## Prerequisites++You need **Node.js 20+** to run the workspace scripts (including `pnpm server:setup`, which both backend and TypeScript contributors use). Install it via [nvm](https://github.com/nvm-sh/nvm), [mise](https://mise.jdx.dev), [fnm](https://github.com/Schniz/fnm), or your package manager (`brew install node` on macOS).++`pnpm` is provisioned automatically via [Corepack](https://nodejs.org/api/corepack.html) (bundled with Node) — the repository pins its version in `package.json`, and the first `pnpm` command will fetch the matching release. If Corepack is disabled in your environment, run `corepack enable` once.++## Spree codebase++Spree is a monorepo with three main areas:++- **`spree/`** — Ruby gems (core, api, admin, emails) distributed as separate packages via RubyGems+- **`packages/`** — TypeScript packages (SDKs, CLI, project scaffolding, docs, React dashboard)+- **`server/`** — A Rails application cloned from [spree-starter](https://github.com/spree/spree-starter) that mounts the local Spree gems (not checked in — `pnpm server:setup` creates it)++## Setup++A single command bootstraps the whole monorepo for both backend and frontend work. You need **Docker** running locally (Docker Desktop, OrbStack, or any compatible runtime) — no Ruby, Postgres, or Redis on your host.++```bash+pnpm install # workspace dependencies+pnpm server:setup # ~5–10 min on first run; idempotent+```++`pnpm server:setup` clones [spree-starter](https://github.com/spree/spree-starter) into `./server/`, wires it to load Spree gems from the monorepo via a Docker compose overlay, builds the dev image, starts the stack (Postgres + Meilisearch + a single Rails `web` container — background jobs run in-process via Solid Queue), and prepares the database. The full sequence lives in `scripts/server-setup.sh`.++When it's done, the backend is up at [http://localhost:3000](http://localhost:3000) and the admin is at [http://localhost:3000/admin](http://localhost:3000/admin). Sign in with the seed admin: **`[email protected]`** / **`spree123`** (override at seed time with `ADMIN_EMAIL` / `ADMIN_PASSWORD` env vars — see `spree/core/app/services/spree/seeds/admin_user.rb`).++Optionally load sample products, taxonomies, and option types:++```bash+pnpm server:load_sample_data+```++## Running a backend day-to-day++After the one-time setup, use these to bring the stack up and down:++```bash+pnpm server:dev # run the stack in the foreground — streams web + worker logs, Ctrl+C stops them+pnpm server:stop # full teardown (also stops postgres / redis / meilisearch)+pnpm server:restart # restart web + worker in place+pnpm server:logs # follow web container logs (when the stack runs detached)+pnpm server:console # open a Rails console inside the container+pnpm server:seed # re-run database seeds+pnpm server:build # rebuild the dev image (only after Dockerfile / .ruby-version changes)+```++`server:dev` behaves like any TS dev server (`vite dev`, the dashboard's `pnpm dev`): it runs in the foreground and Ctrl+C stops the app containers. Postgres, Redis, and Meilisearch keep running for a fast next boot — `pnpm server:stop` shuts everything down.++Run any CLI command against the running backend from `server/`:++```bash+cd server+pnpm exec spree migrate+pnpm exec spree generate model Brand name:string+pnpm exec spree upgrade --plan+```++See the [`@spree/cli` README](https://github.com/spree/spree/blob/main/packages/cli/README.md) for the full command surface.++Which command after which change:++| What changed | What to run |+|---|---|+| Ruby code in `spree/*` gems | Nothing — gems are bind-mounted; code reloads on the next request |+| A new migration in a gem | Nothing — the next `pnpm server:dev` boot applies it (or `cd server && pnpm exec spree migrate` while the stack runs) |+| Gem dependencies (gemspec / Gemfile / lock drift after `git pull`) | Nothing — the next `pnpm server:dev` boot self-heals via `bundle check || bundle install` (or `cd server && pnpm exec spree bundle install` while the stack runs) |+| Compose files / `server/.env` | `pnpm server:dev` (force-recreates the containers) |+| `server/Dockerfile` / `.ruby-version` / starter update that breaks the image build ("lockfile can't be updated because frozen") | `pnpm server:build`, then `pnpm server:dev` — the build script handles the edge-rewritten `Gemfile.lock` automatically |+| Meilisearch image bump ("database version … is incompatible") | Remove the `server_meilisearch_data` volume, boot, then reindex (`pnpm exec spree rake spree:search:reindex`) — the index is derived data |+| Broken beyond repair | `pnpm server:setup` (full reset — wipes the database and volumes) |++Re-run `pnpm server:setup` **only** to fully reset — it does `docker compose down -v` + `rm -rf ./server`, wiping all DB data.++## Native Ruby (advanced)++If you prefer the fastest possible inner loop and don't mind installing Ruby, Postgres, Redis, and Meilisearch on your host directly, you can skip Docker:++```bash+pnpm server:create # clones spree-starter, writes server/.env with SPREE_PATH=..+cd server+bin/setup # installs Ruby (via mise), Postgres/Redis/Meilisearch (via brew bundle on macOS), gems, prepares the database+bin/dev # starts Rails (jobs run in-process) + CSS watchers via Foreman+```++This path is faster per request but means more on your host. It also runs against your installed system services, not a sandboxed Docker stack.++## Backend Development (Ruby)++### Engines overview++The Spree [Rails engines](https://guides.rubyonrails.org/engines.html) live inside `spree/` and are distributed as separate gems (Ruby packages installed via Bundler):++| Engine | Gem | Description |+|---|---|---|+| `core` | `spree_core` | Models, services, business logic |+| `api` | `spree_api` | REST APIs |+| `admin` | `spree_admin` | Admin dashboard |+| `emails` | `spree_emails` | Transactional emails |++### Spree namespace++All Spree models, controllers and other Ruby classes are namespaced by the `Spree` keyword, eg. `Spree::Product`. This means that those files are also located in `spree` sub-directories eg. [app/models/spree/product.rb](https://github.com/spree/spree/blob/main/spree/core/app/models/spree/product.rb).++### Running engine tests++Each engine has its own test suite. First install the shared dependencies at the `spree/` level, then navigate into the specific engine to set up and run its tests:++```bash+# 1. Install shared dependencies+cd spree+bundle install++# 2. Set up and run tests for a specific engine (e.g. core)+cd core+bundle install+bundle exec rake test_app+bundle exec rspec+```++Replace `core` with `api`, `admin`, or `emails` to test other engines.++By default engine tests run against SQLite3. To run against PostgreSQL, set the `DB` environment variable:++```bash+DB=postgres DB_USERNAME=postgres DB_PASSWORD=password DB_HOST=localhost bundle exec rake test_app+```++Run a single spec file:++```bash+cd spree/core+bundle exec rspec spec/models/spree/state_spec.rb+```++Run a specific test by line number:++```bash+cd spree/core+bundle exec rspec spec/models/spree/state_spec.rb:7+```++### Running tests in parallel++For faster test runs on multi-core machines, you can use the `parallel_tests` gem to distribute spec files across multiple CPU cores.++After setting up the test app, create databases for parallel workers:++```bash+cd spree/core+bundle exec rake parallel_setup+```++Then run specs in parallel:++```bash+bundle exec parallel_rspec spec+```++You can also specify the number of workers:++```bash+bundle exec rake "parallel_setup[4]"+bundle exec parallel_rspec -n 4 spec+```++After schema changes, re-run `bundle exec rake parallel_setup` to update the worker databases.++### Integration tests (legacy Rails admin)++The legacy Rails admin (`spree/admin`) ships feature specs that run in a real browser via chromedriver. You only need this if you're touching the legacy admin UI.++Install chromedriver on macOS:++```bash+brew install chromedriver+```++The 6.0 React dashboard (`packages/dashboard`) has its own end-to-end test suite running on Playwright against a real Rails backend — see [Dashboard E2E tests](#dashboard-e2e-tests) under TypeScript Development.++### Performance in development mode++Spree runs slower in development because caching is disabled and code reloads on each request. To turn on caching:++```bash+cd server && pnpm exec spree rails dev:cache+```++Restart the Rails server after running this (Ctrl+C the running `pnpm server:dev` and start it again).++## TypeScript Development++The backend setup is the same as for Ruby work — see [Setup](#setup) above. With `pnpm server:setup` done, the Rails backend is running and you can start the packages you want to work on.++### Packages++| Package | Path | Published | Description |+|---|---|---|---|+| `@spree/sdk` | `packages/sdk` | yes | TypeScript SDK for the Spree Store API |+| `@spree/admin-sdk` | `packages/admin-sdk` | yes | TypeScript SDK for the Spree Admin API |+| `@spree/cli` | `packages/cli` | yes | CLI for managing Spree Commerce projects |+| `create-spree-app` | `packages/create-spree-app` | yes | Project scaffolding (`npm create spree-app`) |+| `@spree/docs` | `packages/docs` | yes | Developer documentation for AI agents and local reference |+| `@spree/dashboard` | `packages/dashboard` | no | React SPA admin dashboard (Spree 6.0, replaces the legacy Rails admin) |+| `@spree/dashboard-core` | `packages/dashboard-core` | no | Framework: registries, providers, generic infra hooks for the dashboard |+| `@spree/dashboard-ui` | `packages/dashboard-ui` | no | Design system used by the dashboard |+| `@spree/sdk-core` | `packages/sdk-core` | no | Shared HTTP/retry/error layer used by both SDKs |++### Common commands++Run from the repository root — [Turborepo](https://turbo.build/) orchestrates tasks across all packages:++| Command | Description |+|---|---|+| `pnpm dev` | Watch mode for all packages (does not boot the backend — use `pnpm server:dev` for that) |+| `pnpm build` | Build all packages (Turbo resolves dependency order) |+| `pnpm test` | Run tests in all packages |+| `pnpm lint` | Lint all packages |+| `pnpm typecheck` | Type-check all packages |+| `pnpm clean` | Remove build artifacts |++### Package-specific commands++You can also run commands in a single package:++```bash+pnpm --filter @spree/sdk test:watch+pnpm --filter @spree/sdk console+pnpm --filter @spree/sdk generate:zod+```++Tests use [Vitest](https://vitest.dev/) with [MSW](https://mswjs.io/) for API mocking at the network level.++### Working on the React dashboard++The dashboard runs as a Vite dev server (port 5173) that proxies `/api/*` to the Rails backend on port 3000 — required for the auth refresh cookie to work over plain HTTP.++```bash+# Terminal 1: backend+pnpm server:dev++# Terminal 2: dashboard+cd packages/dashboard+pnpm dev # http://localhost:5173+```++Sign in with `[email protected]` / `spree123`. To point at a non-default backend, set `VITE_SPREE_API_URL` (also needs to be set at build time for production bundles, not just dev):++```bash+VITE_SPREE_API_URL=https://my-spree.example.com pnpm dev+```++**Gotcha:** the dashboard imports `@spree/admin-sdk` from its **built** `dist/`, not source. If you edit `admin-sdk` (or `sdk-core`, or `sdk`) and want the dashboard to see the changes, run `pnpm build` from the monorepo root first (Turbo-cached). Editing dashboard code alone doesn't need this.++See the [dashboard README](https://github.com/spree/spree/blob/main/packages/dashboard/README.md) for the full architecture (auth, permissions, extension points, the three-package split between `dashboard`, `dashboard-core`, and `dashboard-ui`).++### Dashboard E2E tests++The React dashboard ships an end-to-end suite running on [Playwright](https://playwright.dev/) against a real Rails backend — no mocks. The spec files exercise the full UI: login, staff invitation, invitee signup. CI runs the same suite via the `dashboard-e2e` job in `.github/workflows/packages.yml`.++To run locally you need Ruby (the suite boots a real Rails server) and a one-time browser install:++```bash+# Make sure the dummy Rails app exists (one-time, after a fresh checkout).+cd spree/api+bundle install+bundle exec rake test_app++# Install Playwright's Chromium (one-time per machine).+cd ../../packages/dashboard+pnpm test:e2e:install++# Run the suite. Boots Rails on :3010 + Vite on :5174, runs all specs, tears+# both down. Safe to re-run repeatedly — the SQLite DB resets each run.+pnpm test:e2e+```++For interactive debugging (time-travel through actions, inspect the DOM at each step):++```bash+pnpm test:e2e:ui+```++Filter to a single spec or test name:++```bash+pnpm test:e2e e2e/auth.spec.ts+pnpm test:e2e -g "invites a teammate"+```++When a test fails, Playwright drops a screenshot, video, and DOM snapshot in `packages/dashboard/test-results/<spec>/` — usually enough to diagnose without re-running.++### Type generation++TypeScript types in `packages/sdk/src/types/generated/` (Store API) and `packages/admin-sdk/src/types/generated/` (Admin API) are auto-generated from the Rails serializers using [typelizer](https://github.com/skryukov/typelizer). Zod schemas in `packages/sdk/src/zod/generated/` are derived from the TS types.++A **Lefthook pre-commit hook** regenerates both whenever you commit a change to `spree/api/app/serializers/**/*.rb` and re-stages the generated output. You don't need to run anything manually for the common case.++To regenerate manually (useful when iterating on serializers before committing):++```bash+cd server+pnpm exec spree rake typelizer:generate # regenerate TS types+cd ../packages/sdk+pnpm generate:zod # regenerate Zod schemas+```++If you'd rather avoid the Docker round-trip and have Ruby on your host, the native equivalent works too:++```bash+cd spree/api+bundle install+bundle exec rake typelizer:generate+```++### Releasing packages++Published packages use [Changesets](https://github.com/changesets/changesets) for version management. Each package owns its own `.changeset/` folder, so changesets must be created from inside the package directory:++```bash+cd packages/sdk # or packages/admin-sdk, packages/cli, packages/create-spree-app+pnpm changeset+```++This creates a changeset file describing your changes. Commit it with your PR.++Releasing is a two-step flow: a maintainer consumes the pending changesets (`changeset version` — writes the CHANGELOG and bumps `package.json`) and merges that bump to `main`; the release jobs in `.github/workflows/packages.yml` then detect the unpublished version and publish with npm provenance via Trusted Publishing. `@spree/admin-sdk` publishes under the `next` dist-tag while on the 0.x Developer Preview line; the others ship as `latest` (prereleases go to `beta`).++Private packages (`@spree/dashboard`, `@spree/dashboard-core`, `@spree/dashboard-ui`, `@spree/sdk-core`) don't need changesets.++## Code Style++Consistent code style is enforced via automated linters. Please make sure your changes pass linting before submitting a PR.++**Ruby:** We use [RuboCop](https://rubocop.org/) for Ruby code. The configuration lives in `server/.rubocop.yml` and is shipped with [spree-starter](https://github.com/spree/spree-starter), so it's only available after running `pnpm server:setup`. Run it inside the container via the CLI:++```bash+cd server+pnpm exec spree exec bundle exec rubocop+```++To auto-fix correctable offenses:++```bash+pnpm exec spree exec bundle exec rubocop -a+```++(On the native path, drop the `pnpm exec spree exec` prefix and run `bundle exec rubocop` directly.)++**TypeScript:** We use [Biome](https://biomejs.dev/) for linting and formatting TypeScript code. Run it from the repository root:++```bash+pnpm lint+```++## Making Changes++### Branch naming++Create a new branch for your changes. Do not push changes to the main branch. Branch names should be human-readable and informative:++- Bug fixes: `fix/order-recalculation-total-bug`+- Features: `feature/my-new-amazing-feature`++### Commit messages++Keep your commit history meaningful and clear. Each commit should represent a logical unit of work. [This guide](https://about.gitlab.com/blog/2018/06/07/keeping-git-commit-history-clean/) covers this well.++A few tips:++- Write commit messages in the imperative mood (e.g. "Add feature" not "Added feature")+- Keep the first line under 72 characters+- If your change references a GitHub issue, include `Fixes #<number>` in the commit message or PR description to auto-close it on merge++## Submitting Changes++We use [GitHub Actions](https://github.com/spree/spree/actions) to run CI.++1. Push your changes to a topic branch in your fork of the repository.++ ```bash+ git push origin fix/order-recalculation-total-bug+ ```++2. [Create a Pull Request](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request-from-a-fork) against the `main` branch.++3. Wait for CI to pass.++4. Wait for Spree Core team code review. We aim to review and leave feedback as soon as possible.++### Pull request guidelines++To help us review your PR quickly:++- **Keep PRs focused.** One feature or fix per PR. Smaller PRs are easier to review and merge.+- **Describe your changes.** Explain what you changed and why. Include screenshots for UI changes.+- **Add tests.** All new features and bug fixes should include appropriate test coverage.+- **Update documentation.** If your change affects user-facing behavior, update the relevant docs.+- **Include a changeset** if your change affects a published TypeScript package (`@spree/sdk`, `@spree/admin-sdk`, `@spree/cli`, or `create-spree-app`). Run `pnpm changeset` from inside that package's directory — each package owns its own `.changeset/` folder.+- **Ensure CI passes.** PRs with failing CI will not be reviewed.++## Reporting Bugs++We use [GitHub Issues](https://github.com/spree/spree/issues) to track bugs. Before filing a new issue, please search existing issues to avoid duplicates.++When reporting a bug, please include:++- **Spree version** you're using+- **Steps to reproduce** the problem+- **Expected behavior** vs **actual behavior**+- **Relevant logs or stack traces** (formatted with triple backticks)+- **Your environment** (Ruby version, database, OS)++We have an [issue template](https://github.com/spree/spree/blob/main/.github/ISSUE_TEMPLATE.md) that will guide you through this.++Issues that are open for 14 days without actionable information or activity will be marked as stale and then closed. They can be re-opened if the requested information is provided.++## Using AI Tools for Development++Spree comes with an [AGENTS.md](https://github.com/spree/spree/blob/main/AGENTS.md) file that instructs coding agents like Claude Code or Codex to help you with your development.++We also ship [agent skills](/v5/developer/agentic/agent-skills) (`npx skills add spree/agent-skills`), a [docs MCP server](/v5/developer/agentic/mcp), and [LLM-ready documentation](/v5/developer/agentic/llm-docs) — see the [Agentic Development docs](/v5/developer/agentic/overview) for setup across Claude Code, Cursor, Copilot, and other tools.++The MCP server URL for quick setup:++```+https://spreecommerce.org/docs/mcp+```++## That's a wrap!++Thank you for participating in Open Source and improving Spree - you're awesome!diff --git a/docs/v5/developer/contributing/quickstart.mdx b/docs/v5/developer/contributing/quickstart.mdxnew file mode 100644index 0000000000..b254fe9688--- /dev/null+++ b/docs/v5/developer/contributing/quickstart.mdx@@ -0,0 +1,33 @@+---+title: Contributing quickstart+description: Get started contributing to Spree — fix bugs, add features, build extensions, upgrade old extensions, report issues, and help the community on Discord.+canonical: "https://spreecommerce.org/docs/developer/contributing/quickstart"+---++Spree is an open, community-powered project that anyone can contribute to. There are several ways you can help us improve Spree:++* fixing a bug or creating a new feature+* creating a Spree extension+* upgrading old extensions to recent Spree versions+* helping others on Spree Discord+* submitting an issue describing a bug or a feature request++## Fixing a bug or creating a new feature++Before diving into the Spree codebase we recommend you spend some time reviewing the [Core Concepts section](/core-concepts) which will help you understand how Spree works under the hood.++After you're done with that please follow to [Developing Spree guide](developing-spree)++To find issues you can tackle on we recommend visiting [Spree Contribute page](https://github.com/spree/spree/contribute) which lists issues tagged with [Good First Issue label](https://github.com/spree/spree/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+First+Issue%22). Those bugs or features are great starting points into Open Source development.++## Creating a Spree extension++Extensions provide additional features and integrations for your Spree store. You can create your own and share with the rest of the community. Before doing so please check our [Integrations directory](/integrations) if your desired integration does not exist already. If not [follow the Creating an Extension tutorial](/v5/developer/contributing/creating-an-extension) to learn how to create one.++## Helping others on Spree Discord++Last but not least, you're invited to [join our Discord](https://discord.spreecommerce.org) to help and receive guidance from fellow Spree developers including Spree Core Team.++## Submitting issues++You can [submit an issue](https://github.com/spree/spree/issues/new/choose) on our [Github Issues tracker](https://github.com/spree/spree/issues)diff --git a/docs/v5/developer/core-concepts/addresses.mdx b/docs/v5/developer/core-concepts/addresses.mdxnew file mode 100644index 0000000000..6354e35d1f--- /dev/null+++ b/docs/v5/developer/core-concepts/addresses.mdx@@ -0,0 +1,290 @@+---+title: Addresses+description: How Spree models addresses, countries, states, and zones, and how geographic data drives checkout, tax calculation, and shipping rates.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/addresses"+---++## Overview++Geography is central to how Spree handles checkout, pricing, taxes, and shipping. The system works through a chain of related concepts:++```+Markets → Countries → Zones → Tax Rates & Shipping Methods+ ↘ States+ ↘ Addresses+```++- [**Markets**](/v5/developer/core-concepts/markets) group countries into selling regions with their own currency and locale+- **Countries** and **States** provide the geographic data for addresses+- **Zones** group countries or states together to define where tax rates and shipping methods apply+- **Addresses** tie a customer to a specific location, determining which zones — and therefore which taxes and shipping options — apply to their order++## Addresses++An address represents a shipping or billing location. Every order has a shipping address and a billing address, and customers can save multiple addresses in their address book.++| Field | Description |+|-------|-------------|+| `first_name`, `last_name` | Contact name |+| `address1`, `address2` | Street address |+| `city` | City |+| `postal_code` | Postal code (not required for all countries) |+| `phone` | Phone number |+| `company` | Company name (optional) |+| `country_iso` | Country (ISO alpha-2 code, e.g., `US`) |+| `state_abbr` | State/province abbreviation (required for some countries, e.g., `CA`) |++Whether a state or zipcode is required depends on the country. For example, the US requires both, while Hong Kong requires neither. The API returns `states_required` and `zipcode_required` on each country so your frontend can adapt the form dynamically.++### Customer Address Book++Customers can save multiple addresses and set a default for shipping and billing. When a customer completes checkout, the selected addresses are cloned onto the order — so editing an address later doesn't change past orders.++<CodeGroup>++```typescript Store SDK+// List addresses+const { data: addresses } = await client.customer.addresses.list()++// Create an address+const address = await client.customer.addresses.create({+ first_name: 'John',+ last_name: 'Doe',+ address1: '123 Main St',+ city: 'Los Angeles',+ country_iso: 'US',+ state_abbr: 'CA',+ postal_code: '90001',+ phone: '555-0100',+})++// Update an address+await client.customer.addresses.update('addr_xxx', { city: 'Brooklyn' })++// Delete an address+await client.customer.addresses.delete('addr_xxx')++// Set as default shipping or billing address — pass the boolean flags to create or update+await client.customer.addresses.update('addr_xxx', { is_default_shipping: true })+await client.customer.addresses.update('addr_xxx', { is_default_billing: true })+```++```bash cURL+# List addresses+curl 'https://api.mystore.com/api/v3/store/customers/me/addresses' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'Authorization: Bearer <jwt_token>'++# Create an address+curl -X POST 'https://api.mystore.com/api/v3/store/customers/me/addresses' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'Authorization: Bearer <jwt_token>' \+ -H 'Content-Type: application/json' \+ -d '{+ "first_name": "John",+ "last_name": "Doe",+ "address1": "123 Main St",+ "city": "Los Angeles",+ "country_iso": "US",+ "state_abbr": "CA",+ "postal_code": "90001",+ "phone": "555-0100"+ }'++# Update an address+curl -X PATCH 'https://api.mystore.com/api/v3/store/customers/me/addresses/addr_xxx' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'Authorization: Bearer <jwt_token>' \+ -H 'Content-Type: application/json' \+ -d '{ "city": "Brooklyn" }'++# Delete an address+curl -X DELETE 'https://api.mystore.com/api/v3/store/customers/me/addresses/addr_xxx' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'Authorization: Bearer <jwt_token>'+```++</CodeGroup>++### Checkout Addresses++During checkout, you can either reference a saved address by ID or pass a new address inline. See the [cart and checkout SDK guide](/v5/developer/sdk/store/cart-checkout) for the full flow of passing addresses during checkout:++<CodeGroup>++```typescript Store SDK+// Use saved addresses+await client.carts.update(cartId, {+ shipping_address_id: 'addr_xxx',+ billing_address_id: 'addr_yyy',+})++// Or pass new addresses inline+await client.carts.update(cartId, {+ shipping_address: {+ first_name: 'John',+ last_name: 'Doe',+ address1: '123 Main St',+ city: 'Los Angeles',+ country_iso: 'US',+ state_abbr: 'CA',+ postal_code: '90001',+ phone: '555-0100',+ },+})+```++```bash cURL+# Use a saved address+curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Token: order_token' \+ -H 'Content-Type: application/json' \+ -d '{ "shipping_address_id": "addr_xxx", "billing_address_id": "addr_yyy" }'++# Or pass a new address inline+curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Token: order_token' \+ -H 'Content-Type: application/json' \+ -d '{+ "shipping_address": {+ "first_name": "John",+ "last_name": "Doe",+ "address1": "123 Main St",+ "city": "Los Angeles",+ "country_iso": "US",+ "state_abbr": "CA",+ "postal_code": "90001",+ "phone": "555-0100"+ }+ }'+```++</CodeGroup>++## Countries++Countries are the foundation of Spree's geographic system. They connect to [Markets](/v5/developer/core-concepts/markets), contain states, and belong to zones.++Each country includes metadata that drives address form behavior:++| Field | Description | Example |+|-------|-------------|---------|+| `iso` | ISO 3166-1 alpha-2 code | `US` |+| `iso3` | ISO 3166-1 alpha-3 code | `USA` |+| `name` | Country name | `United States` |+| `states_required` | Whether the address form should show a state/province picker | `true` |+| `zipcode_required` | Whether the address form should require a postal code | `true` |++### Which Countries Are Available?++Only countries assigned to a [Market](/v5/developer/core-concepts/markets) are available during checkout. This lets you control exactly where you sell.++<CodeGroup>++```typescript Store SDK+// List all countries available in this store+const { data: countries } = await client.countries.list()++// Get a country with its states (for address form dropdowns)+const usa = await client.countries.get('US', { expand: ['states'] })+// usa.states => [{ name: "Alabama", abbr: "AL" }, { name: "Alaska", abbr: "AK" }, ...]++// Get a country with its market (for currency/locale resolution)+const germany = await client.countries.get('DE', { expand: ['market'] })+// germany.market => { currency: "EUR", default_locale: "de", tax_inclusive: true }+```++```typescript Admin SDK+const { data: countries } = await adminClient.countries.list()++const usa = await adminClient.countries.get('US')+```++```bash cURL+# List all countries+curl 'https://api.mystore.com/api/v3/store/countries' \+ -H 'X-Spree-API-Key: pk_xxx'++# Get a country with states+curl 'https://api.mystore.com/api/v3/store/countries/US?expand=states' \+ -H 'X-Spree-API-Key: pk_xxx'++# Get a country with its market+curl 'https://api.mystore.com/api/v3/store/countries/DE?expand=market' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++Use the `states_required` and `zipcode_required` fields to build adaptive address forms — show a state picker only when needed, and skip the zipcode field for countries that don't use them.++## States++States (provinces, regions) belong to a country and are used for address validation and zone matching. Countries like the US, Canada, Australia, and India have predefined states — for these countries, customers must select a state from the list rather than typing a name.++States are fetched via the country endpoint using [`?expand=states`](/api-reference/store-api/relations):++<CodeGroup>++```typescript Store SDK+const usa = await client.countries.get('US', { expand: ['states'] })++// Build a state picker from the response+usa.states.forEach(state => {+ console.log(state.abbr, state.name) // "AL", "Alabama"+})+```++```typescript Admin SDK+const usa = await adminClient.countries.get('US', { expand: ['states'] })+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/countries/US?expand=states' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++For countries without predefined states, addresses accept a free-text `state_name` field instead of `state_abbr`.++## Zones++Zones group countries or states together for [tax](/v5/developer/core-concepts/taxes) and [shipping](/v5/developer/core-concepts/shipments) rules. A zone is either **country-based** or **state-based**.++**Examples:**+- **EU VAT** (country zone) — Germany, France, Italy, Spain, ... → applies EU VAT rates+- **California** (state zone) — CA → applies California sales tax+- **Domestic Shipping** (country zone) — US, CA → enables domestic shipping methods++When a customer enters their address at checkout, Spree matches it against zones to determine:+1. Which **tax rates** apply (see [Taxes](/v5/developer/core-concepts/taxes))+2. Which **shipping methods** are available (see [Shipments](/v5/developer/core-concepts/shipments))++Zones are configured in the admin dashboard — storefront developers don't interact with them directly via the API.++### Tax Zones and Markets++Each [Market](/v5/developer/core-concepts/markets) resolves a tax zone from its default country. This means product prices display the correct tax treatment (inclusive or exclusive) before the customer enters an address — just from knowing their market.++## How It All Fits Together++Here's how geography flows through a typical checkout:++1. **Customer visits the store** — their country is detected (from URL, geolocation, or selection)+2. **Market resolved** — the country maps to a market, which sets the currency and locale+3. **Products displayed** — prices use the market's currency and tax zone for correct formatting+4. **Customer enters address** — the address form adapts based on `states_required` and `zipcode_required`+5. **Zones matched** — the shipping address determines which tax rates and shipping methods apply+6. **Order completed** — the address is cloned onto the order for permanent record++## Related Documentation++- [Markets](/v5/developer/core-concepts/markets) — Multi-region commerce with currency, locale, and country grouping+- [Taxes](/v5/developer/core-concepts/taxes) — How zones and addresses affect taxation+- [Shipments](/v5/developer/core-concepts/shipments) — How zones and addresses affect shipping availability+- [Orders](/v5/developer/core-concepts/orders) — Order billing and shipping addresses+- [Account SDK guide](/v5/developer/sdk/store/account) — Managing the logged-in customer's address book with `client.customer.addresses`+- [Store API authentication](/api-reference/store-api/authentication) — How to obtain and send the customer JWT (`Authorization: Bearer` header)diff --git a/docs/developer/core-concepts/adjustments.mdx b/docs/v5/developer/core-concepts/adjustments.mdxsimilarity index 74%rename from docs/developer/core-concepts/adjustments.mdxrename to docs/v5/developer/core-concepts/adjustments.mdxindex 3abfcfe726..b9b6da2fee 100644--- a/docs/developer/core-concepts/adjustments.mdx+++ b/docs/v5/developer/core-concepts/adjustments.mdx@@ -1,11 +1,12 @@---title: Adjustmentsdescription: How Spree adjustments apply taxes, promotions, and other price modifications to orders, line items, and shipments, and how totals are recalculated.+canonical: "https://spreecommerce.org/docs/v5/developer/core-concepts/adjustments"---## Overview-An Adjustment modifies the price of an [Order](/developer/core-concepts/orders), a [Line Item](/developer/core-concepts/orders#line-items), or a [Shipment](/developer/core-concepts/shipments). Adjustments can be positive (charges) or negative (credits).+An Adjustment modifies the price of an [Order](/v5/developer/core-concepts/orders), a [Line Item](/v5/developer/core-concepts/orders#line-items), or a [Shipment](/v5/developer/core-concepts/shipments). Adjustments can be positive (charges) or negative (credits).```mermaiderDiagram@@ -31,7 +32,7 @@ erDiagram**Key relationships:**- **Adjustment** modifies prices on orders, line items, or shipments-- **Source** is where the adjustment comes from ([Tax Rate](/developer/core-concepts/taxes) or [Promotion Action](/developer/core-concepts/promotions))+- **Source** is where the adjustment comes from ([Tax Rate](/v5/developer/core-concepts/taxes) or [Promotion Action](/v5/developer/core-concepts/promotions))- **Adjustable** is what's being adjusted (Order, LineItem, or Shipment)- Positive amounts are charges, negative amounts are credits@@ -48,8 +49,8 @@ Adjustments are created by two sources:| Source | Example | Typical Amount ||--------|---------|----------------|-| [Tax Rate](/developer/core-concepts/taxes) | Sales tax, VAT | Positive (charge) |-| [Promotion Action](/developer/core-concepts/promotions) | Coupon discount, free shipping | Negative (credit) |+| [Tax Rate](/v5/developer/core-concepts/taxes) | Sales tax, VAT | Positive (charge) |+| [Promotion Action](/v5/developer/core-concepts/promotions) | Coupon discount, free shipping | Negative (credit) |## Adjustment Attributes@@ -108,8 +109,8 @@ curl 'https://api.mystore.com/api/v3/store/orders/or_abc123?expand=items,fulfill## Related Documentation-- [Promotions](/developer/core-concepts/promotions) — Promotion-based adjustments-- [Taxes](/developer/core-concepts/taxes) — Tax adjustments-- [Shipments](/developer/core-concepts/shipments) — Shipping adjustments-- [Orders](/developer/core-concepts/orders) — How adjustments affect order totals-- [Calculators](/developer/core-concepts/calculators) — How tax rate and promotion action amounts are computed+- [Promotions](/v5/developer/core-concepts/promotions) — Promotion-based adjustments+- [Taxes](/v5/developer/core-concepts/taxes) — Tax adjustments+- [Shipments](/v5/developer/core-concepts/shipments) — Shipping adjustments+- [Orders](/v5/developer/core-concepts/orders) — How adjustments affect order totals+- [Calculators](/v5/developer/core-concepts/calculators) — How tax rate and promotion action amounts are computeddiff --git a/docs/v5/developer/core-concepts/architecture.mdx b/docs/v5/developer/core-concepts/architecture.mdxnew file mode 100644index 0000000000..12d56b5113--- /dev/null+++ b/docs/v5/developer/core-concepts/architecture.mdx@@ -0,0 +1,181 @@+---+title: Architecture+description: Explore how Spree's core models, APIs, and gems fit together — catalog, shopping, checkout, fulfillment, and pricing — for headless or embedded commerce.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/architecture"+---++## Overview++Spree is a commerce engine built around interconnected models that represent the core concepts of commerce: products, orders, payments, and shipments. It adapts to your stack — use it as a headless API for any frontend, embed it into an existing application, or scale it from a single storefront to a global multi-vendor marketplace.++<Info>+ Spree supports PostgreSQL, MySQL, and SQLite. PostgreSQL is recommended for production. [Learn more about database configuration](/v5/developer/deployment/database).+</Info>++## Core Commerce Flow++The following diagram shows how the main models interact during a typical customer purchase:++```mermaid+flowchart TB+ subgraph Catalog["Catalog"]+ Product --> Variant+ Variant --> Price+ Variant --> StockItem+ StockItem --> StockLocation+ end++ subgraph Shopping["Shopping"]+ User --> Order+ Order --> LineItem+ LineItem --> Variant+ end++ subgraph Checkout["Checkout"]+ Order --> Address+ Order --> Shipment+ Order --> Payment+ Shipment --> ShippingMethod+ Payment --> PaymentMethod+ end++ subgraph Fulfillment["Fulfillment"]+ Shipment --> InventoryUnit+ InventoryUnit --> Variant+ StockLocation --> Shipment+ end++ subgraph Pricing["Pricing & Adjustments"]+ Order --> Adjustment+ LineItem --> Adjustment+ Shipment --> Adjustment+ TaxRate --> Adjustment+ Promotion --> Adjustment+ end+```++**How it works:**++1. **Catalog** — [Products](/v5/developer/core-concepts/products) have [Variants](/v5/developer/core-concepts/products#variants) (SKUs) with prices and inventory tracked at [Stock Locations](/v5/developer/core-concepts/inventory#stock-locations)++2. **Shopping** — Customers add Variants to their cart, creating an [Order](/v5/developer/core-concepts/orders) with Line Items++3. **Checkout** — The Order collects [Addresses](/v5/developer/core-concepts/addresses), calculates [Shipping](/v5/developer/core-concepts/shipments) options, and processes [Payments](/v5/developer/core-concepts/payments)++4. **Fulfillment** — [Shipments](/v5/developer/core-concepts/shipments) are created from Stock Locations, tracking individual [Inventory Units](/v5/developer/core-concepts/inventory#inventory-units)++5. **Pricing & Adjustments** — [Taxes](/v5/developer/core-concepts/taxes) and [Promotions](/v5/developer/core-concepts/promotions) create [Adjustments](/v5/developer/core-concepts/adjustments) that modify order totals++## Core Model Relationships++This diagram shows the key database relationships between Spree's main models:++```mermaid+erDiagram+ Store ||--o{ Order : "has many"+ Store ||--o{ Product : "has many"++ Product ||--o{ Variant : "has many"+ Product }o--|| TaxCategory : "belongs to"+ Product }o--|| ShippingCategory : "belongs to"+ Product }o--o{ Taxon : "categorized by"++ Variant ||--o{ Price : "has many"+ Variant ||--o{ StockItem : "has many"+ Variant ||--o{ LineItem : "has many"++ Order ||--o{ LineItem : "has many"+ Order ||--o{ Shipment : "has many"+ Order ||--o{ Payment : "has many"+ Order ||--o{ Adjustment : "has many"+ Order }o--|| User : "belongs to"+ Order }o--|| Address : "ship address"+ Order }o--|| Address : "bill address"++ Shipment ||--o{ InventoryUnit : "has many"+ Shipment }o--|| StockLocation : "ships from"+ Shipment }o--|| ShippingMethod : "via"++ Payment }o--|| PaymentMethod : "via"++ StockLocation ||--o{ StockItem : "has many"++ TaxRate }o--|| TaxCategory : "belongs to"+ TaxRate }o--|| Zone : "applies to"+ TaxRate ||--o{ Adjustment : "creates"++ Promotion ||--o{ Adjustment : "creates"+```++## APIs++Spree exposes two REST APIs:++| API | Purpose | Authentication |+|-----|---------|----------------|+| [**Store API**](/api-reference/store-api/introduction) | Customer-facing — cart, checkout, products, account | [Publishable API key + JWT](/api-reference/store-api/authentication) |+| [**Admin API**](/api-reference/admin-api/introduction) | Operational — manage products, orders, customers, settings | [Secret API key](/api-reference/admin-api/authentication) + JWT |++Both APIs share the same list shapes, filtering, querying, and pagination, and offer fully typed TypeScript clients — [@spree/sdk](/v5/developer/sdk/quickstart) for the Store API and [@spree/admin-sdk](/v5/developer/sdk/admin/quickstart) for the Admin API.++Events from both APIs can trigger [Webhooks](/v5/developer/core-concepts/webhooks) to notify external systems in real time.++## Multi-Store Architecture++Spree supports running [multiple storefronts](/v5/developer/multi-tenant/quickstart) from a single installation. Each Store can have:++- Its own domain and branding+- Different currencies and locales+- Separate product catalogs+- Independent payment and shipping methods+- Isolated orders and customers++This makes Spree suitable for multi-brand retailers, international expansion, or B2B/B2C hybrid setups.++## Extension Points++Spree is designed to be customized without modifying core code. The main extension mechanisms are:++| Mechanism | Use Case | Documentation |+|-----------|----------|---------------|+| **Events & Subscribers** | React to order completion, payment, shipment events | [Events Guide](/v5/developer/core-concepts/events) |+| **Webhooks** | Notify external systems of changes | [Webhooks Guide](/v5/developer/core-concepts/webhooks) |+| **Dependencies** | Swap out services (tax calculation, shipping estimation) | [Dependencies Guide](/v5/developer/customization/dependencies) |+| **Decorators** | Modify existing core models & classes behavior (use sparingly) | [Decorators Guide](/v5/developer/customization/decorators) |++<Info>+For most customizations, prefer **Events** and **Dependencies** over Decorators. They're easier to maintain and won't break during upgrades.+</Info>++## Packages++Spree is distributed as a set of packages:++**Core (required):**++| Package | Purpose |+|---------|---------|+| `spree` | Models, services, business logic, Store API, Admin API, and Webhooks |++**Optional:**++| Package | Purpose |+|---------|---------|+| `spree_admin` | Admin dashboard for managing your store |+| `spree_emails` | Transactional email templates (order confirmation, shipping, etc.) |++**TypeScript packages:**++| Package | Purpose |+|---------|---------|+| [`@spree/sdk`](/v5/developer/sdk/quickstart) | TypeScript SDK for the Store API |+| [`@spree/admin-sdk`](/v5/developer/sdk/admin/quickstart) | TypeScript SDK for the Admin API |+| [`@spree/cli`](/v5/developer/cli/quickstart) | Command line interface for managing local environment and using the Admin API from the terminal |++## Related Documentation++- [Products](/v5/developer/core-concepts/products) — Product catalog and variants+- [Orders](/v5/developer/core-concepts/orders) — Order lifecycle and state machine+- [Payments](/v5/developer/core-concepts/payments) — Payment processing+- [Shipments](/v5/developer/core-concepts/shipments) — Shipping and fulfillment+- [Customization Quickstart](/v5/developer/customization/quickstart) — How to extend Spreediff --git a/docs/v5/developer/core-concepts/calculators.mdx b/docs/v5/developer/core-concepts/calculators.mdxnew file mode 100644index 0000000000..be25598e6f--- /dev/null+++ b/docs/v5/developer/core-concepts/calculators.mdx@@ -0,0 +1,305 @@+---+title: Calculators+canonical: "https://spreecommerce.org/docs/developer/core-concepts/calculators"+---++## Overview++### Calculator Model Diagram++```mermaid+erDiagram+ Calculator {+ string type+ string calculable_type+ text preferences+ }++ TaxRate {+ string name+ decimal amount+ boolean included_in_price+ }++ ShippingMethod {+ string name+ string display_on+ }++ PromotionAction {+ string type+ }++ Adjustment {+ decimal amount+ string label+ }++ TaxRate ||--|| Calculator : "has one"+ ShippingMethod ||--|| Calculator : "has one"+ PromotionAction ||--|| Calculator : "has one"+ TaxRate ||--o{ Adjustment : "creates"+ ShippingMethod ||--o{ ShippingRate : "calculates"+ PromotionAction ||--o{ Adjustment : "creates"+```++**Key relationships:**+- **Calculator** computes amounts for various features+- Used by **[Tax Rates](/v5/developer/core-concepts/taxes)** to calculate tax amounts+- Used by **[Shipping Methods](/v5/developer/core-concepts/shipments)** to calculate shipping costs+- Used by **[Promotion Actions](/v5/developer/core-concepts/promotions)** to calculate discounts+- Calculators store [preferences (rates, percentages, etc.)](/v5/developer/customization/model-preferences) for their calculations++Spree makes extensive use of the `Spree::Calculator` model and there are several subclasses provided to deal with various types of calculations flat rate, percentage discount, sales tax, VAT, etc. All calculators extend the `Spree::Calculator` class and must provide the following methods:++```ruby+def self.description+ # Human readable description of the calculator+end++def compute(object=nil)+ # Returns the value after performing the required calculation+end+```++Calculators link to a `calculable` object, which are typically one of `Spree::ShippingMethod`, `Spree::TaxRate`, or `Spree::Promotion::Actions::CreateAdjustment`. These three classes use the `Spree::CalculatedAdjustments` module described below to provide an easy way to calculate adjustments for their objects.++## Available Calculators++The following are descriptions of the currently available calculators in Spree. If you would like to add your own, please see the [Creating a New Calculator](#creating-a-new-calculator) section.++### Default Tax++For information about this calculator, please read the [Taxes](/v5/developer/core-concepts/taxes) guide.++### Flat Percent Per Item Total++This calculator has one preference: `flat_percent` and can be set like this:++```ruby+calculator.preferred_flat_percent = 10+```++This calculator takes an order and calculates an amount using this calculation:++```ruby+[item total] x [flat percentage]+```++For example, if an order had an item total of `$31` and the calculator was configured to have a flat percent amount of `10`, the discount would be `$3.10`, because `$31 x 10% = $3.10`.++### Flat Rate++This calculator can be used to provide a flat rate discount.++This calculator has two preferences: `amount` and `currency`. These can be set like this:++```ruby+calculator.preferred_amount = 10+calculator.preferred_currency = "USD"+```++The currency for this calculator is used to check to see if a shipping method is available for an order. If an order's currency does not match the shipping method's currency, then that shipping method will not be displayed on the frontend.++This calculator can take any object and will return simply the preferred amount.++### Flexi Rate++This calculator is typically used for promotional discounts when you want a specific discount for the first product, and then subsequent discounts for other products, up to a certain amount.++This calculator takes three preferences:++* `first_item`: The discounted price of the first items.+* `additional_item`: The discounted price of subsequent items.+* `max_items`: The maximum number of items this discount applies to.++The calculator computes based on this:++```text+[first item discount] + (([items_count*] - 1) x [additional item discount])+```++* up to the `max_items`++Thus, if you have ten items in your shopping cart, your `first_item` preference is set to `$10`, your `additional_items` preference is set to `$5`, and your `max_items` preference is set to `4`, the total discount would be `$25`:++* `$10` for the first item+* `$5` for each of the `3` subsequent items: `$5 \* 3 = $15`+* `$0` for the remaining `6` items++### Per Item++The Per Item calculator (`Spree::Calculator::Shipping::PerItem`) is a shipping calculator that charges a flat amount for every item in a shipment.++This calculator takes two preferences:++* `amount`: The flat amount charged per item.+* `currency`: The currency for this calculator.++It computes a flat rate per item by multiplying the `amount` preference by the total item quantity in the shipment package:++```text+[amount] x [total item quantity in package]+```++For example, with an `amount` of `5` and a package containing `3` items in total, the calculator computes an amount of `15` (`5 x 3`).++### Percent Per Item++The Percent Per Item calculator (`Spree::Calculator::PercentOnLineItem`) applies a percentage discount to a single line item. It takes two preferences:++* `percent`: The percentage to apply to the line item's amount.+* `apply_only_on_full_priced_items`: When enabled, skips line items that are already on sale.++For each line item, the calculator computes `line item amount` x `percent` / `100`, capped at the line item's amount so a promotion adjustment never pushes the total negative.++For example, a `$30` line item at `10%` yields a `$3` discount (`$30 x 10% = $3`).++### Price Sack++The Price Sack calculator is useful for when you want to provide a discount for an order which is over a certain price. The calculator has four preferences:++* `minimal_amount`: The minimum amount for the line items total to trigger the calculator.+* `discount_amount`: The amount to discount from the order if the line items total is equal to or greater than the `minimal_amount`.+* `normal_amount`: The amount to discount from the order if the line items total is less than the `minimal_amount`.+* `currency`: The currency for this calculator. Defaults to the store currency++Suppose you have a Price Sack calculator with a `minimal_amount` preference of `$50`, a `normal_amount` preference of `$2`, and a `discount_amount` of `$5`. An order with a line items total of `$60` would result in a discount of `$5` for the whole order. An order of `$20` would result in a discount of `$2`.++## Creating a New Calculator++To create a new calculator for Spree, you need to do two things. The first is to inherit from the `Spree::Calculator` class and define `description` and `compute` methods on that class:++```ruby+class CustomCalculator < Spree::Calculator+ def self.description+ # Human readable description of the calculator+ end++ def compute(object=nil)+ # Returns the value after performing the required calculation+ end+end+```++If you are creating a new calculator for shipping methods, please be aware that you need to inherit from `Spree::ShippingCalculator` instead, and define a `compute_package` method:++```ruby+class CustomCalculator < Spree::ShippingCalculator+ def self.description+ # Human readable description of the calculator+ end++ def compute_package(package)+ # Returns the value after performing the required calculation+ end+end+```++The second thing is to register this calculator as a tax, shipping, or promotion adjustment calculator by calling code like this at the end of `config/initializers/spree.rb` inside your application `config` variable defined for brevity:++<Tabs>+ <Tab title="Spree 5.2+">+ ```ruby config/initializers/spree.rb+ Rails.application.config.after_initialize do+ Spree.calculators.tax_rates << CustomCalculator+ Spree.calculators.shipping_methods << CustomCalculator+ Spree.calculators.promotion_actions_create_adjustments << CustomCalculator+ end+ ```+ </Tab>+ <Tab title="Spree 5.1 and below">+ ```ruby config/initializers/spree.rb+ Rails.application.config.spree.calculators.tax_rates << CustomCalculator+ Rails.application.config.spree.calculators.shipping_methods << CustomCalculator+ Rails.application.config.spree.calculators.promotion_actions_create_adjustments << CustomCalculator+ ```+ </Tab>+</Tabs>++For example if your calculator is placed in `app/models/spree/calculator/shipping/my_own_calculator.rb` you should call:++<Tabs>+ <Tab title="Spree 5.2+">+ ```ruby config/initializers/spree.rb+ Rails.application.config.after_initialize do+ Spree.calculators.shipping_methods << Spree::Calculator::Shipping::MyOwnCalculator+ end+ ```+ </Tab>+ <Tab title="Spree 5.1 and below">+ ```ruby config/initializers/spree.rb+ Rails.application.config.spree.calculators.shipping_methods << Spree::Calculator::Shipping::MyOwnCalculator+ ```+ </Tab>+</Tabs>++### Determining Availability++By default, all shipping method calculators are available at all times. If you wish to make this dependent on something from the order, you can re-define the `available?` method inside your calculator:++```ruby app/models/custom_calculator.rb+class CustomCalculator < Spree::Calculator+ def available?(object)+ object.currency == "USD"+ end+end+```++## Calculated Adjustments++If you wish to use Spree's calculator functionality for your own application, you can include the `Spree::CalculatedAdjustments` module into a model of your choosing.++```ruby app/models/plan.rb+class Plan < ActiveRecord::Base+ include Spree::CalculatedAdjustments+end+```++To have calculators available for this class, you will need to register them. `Spree.calculators` is a fixed-member struct (`SpreeCalculators`, defined in `spree/core/lib/spree/core/engine.rb`) that exposes only the four built-in buckets:++* `shipping_methods`+* `tax_rates`+* `promotion_actions_create_adjustments`+* `promotion_actions_create_item_adjustments`++`Plan.calculators` internally calls `Spree.calculators.send(:plans)` (the tableized model name), so both registration and lookup raise `NoMethodError` until you extend the struct to add a matching `plans` member. Ruby structs cannot gain members at runtime, so this means redefining the `SpreeCalculators` struct (or reassigning `Spree.calculators` to an object that responds to `plans`) before you register anything onto it.++Once the struct exposes a `plans` member you can register calculators:++<Tabs>+ <Tab title="Spree 5.2+">+ ```ruby config/initializers/spree.rb+ Rails.application.config.after_initialize do+ Spree.calculators.plans << CustomCalculator+ end+ ```+ </Tab>+ <Tab title="Spree 5.1 and below">+ ```ruby config/initializers/spree.rb+ Rails.application.config.spree.calculators.plans << CustomCalculator+ ```+ </Tab>+</Tabs>++Then you can access these calculators by calling this method:++```ruby+Plan.calculators+```++Using this method, you can then display the calculators as you please. Each object for this new class will need to have a calculator associated so that adjustments can be calculated on them.++`Spree::CalculatedAdjustments` provides a `has_one :calculator` association (with `accepts_nested_attributes_for` and a presence validation), delegates `compute` to that calculator, exposes a `with_calculator` scope, `calculator_type` / `calculator_type=` accessors, and the `Plan.calculators` registry shown above. To work out what the calculator would compute an amount to be, call `compute` on an instance:++```ruby+plan.compute(<calculable object>)+```++The module does not define `create_adjustment`, `update_adjustment`, or `compute_amount`. If you also need to build adjustments, include `Spree::AdjustmentSource`, which adds `create_adjustment(order, adjustable, included = false)`. That method calls a `compute_amount` you define on the including model (as `Spree::TaxRate` and the `Spree::Promotion::Actions` classes do). There is no `update_adjustment` method in core.++## Related Documentation++- [Adjustments](/v5/developer/core-concepts/adjustments) — the records calculators compute amounts for.+- [Dependencies](/v5/developer/customization/dependencies) — swap out calculators via the Dependencies system.+diff --git a/docs/v5/developer/core-concepts/channels.mdx b/docs/v5/developer/core-concepts/channels.mdxnew file mode 100644index 0000000000..7f81c4fd4f--- /dev/null+++ b/docs/v5/developer/core-concepts/channels.mdx@@ -0,0 +1,234 @@+---+title: Channels+description: Per-store distribution surfaces — online storefront, POS, marketplace, wholesale — each with its own product catalog and order attribution.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/channels"+---++import { Since } from '/snippets/since.mdx';++<Since version="5.5" />++## Overview++Channels segment a single [Store](/v5/developer/core-concepts/stores) into distinct selling surfaces. A channel represents *where* an order originates from — the online storefront, an in-person point-of-sale till, a marketplace integration (Amazon, eBay), a B2B wholesale portal, a mobile app — and *which* subset of the store's products is available there.++Every store ships with one default channel named *Online Store*. You can add more from **Settings → Sales channels** in the admin dashboard.++## Channel Attributes++| Attribute | Description | Example |+|-----------|-------------|---------|+| `name` | Human-readable name, displayed in the admin and reports | `Point of Sale` |+| `code` | URL-safe slug, stable identifier sent via the `X-Spree-Channel` header | `pos` |+| `active` | When `false`, the channel stops accepting orders | `true` |+| `default` | Exactly one channel per store is the default. Used as a fallback when no channel header is present and as the auto-publish target for new products | `true` |+| `storefront_access` | Controls what an anonymous visitor may see: `public`, `prices_hidden`, or `login_required`. Unset inherits the store's setting. See [Storefront Access Gating](#storefront-access-gating) | `login_required` |+| `guest_checkout` | Whether an order may be placed without an account on this channel. Unset inherits the store's setting | `false` |+| `preferred_order_routing_strategy` | Optional per-channel override of the store's [Order Routing](/v5/developer/core-concepts/shipments#order-routing) strategy | `Spree::OrderRouting::Strategy::Rules` |++`code` is normalized to a URL-safe slug on save — `POS` becomes `pos`, `Point of Sale!` becomes `point-of-sale`. Leaving `code` blank derives it from `name`.++## How Channels Work++### Resolution at request time++Every incoming Store API or storefront request resolves to a channel:++1. If the `X-Spree-Channel` header is present, the value is matched against `channels.code` — or `channels.id` when the value looks like a prefixed ID (`ch_…`) — scoped to the current store.+2. Otherwise, the store's default channel is used.++The resolved channel is then available to controllers, models, and serializers throughout the request.++### Selecting a channel from the Store SDK++The Store SDK sends `X-Spree-Channel` on every request when configured. The value can be either the channel `code` (merchant-meaningful, recommended) or the prefixed ID (`ch_…`). `setChannel` is a sticky setter that [mirrors `setLocale` / `setCurrency` / `setCountry`](/v5/developer/sdk/configuration).++<CodeGroup>++```typescript Store SDK+// Client-level default+const client = createClient({+ baseUrl: 'https://api.mystore.com',+ publishableKey: 'pk_xxx',+ channel: 'pos',+})++// Sticky setter (mirrors setLocale / setCurrency / setCountry)+client.setChannel('wholesale')++// Per-request override+const products = await client.products.list({}, { channel: 'pos' })+```++```typescript Admin SDK+// admin filters by the channel's code via Ransack (q[channels_code_eq])+const { data: products } = await adminClient.products.list({ channels_code_eq: 'pos' })+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Channel: pos'+```++</CodeGroup>++The Admin API does not consume `X-Spree-Channel` — admin endpoints return data across all channels for the current store. [Filter by channel on the admin side via Ransack](/api-reference/admin-api/querying) (`q[channel_id_eq]=ch_xxx` for orders, `q[channels_id_in][]=ch_xxx` for products).++### Product visibility++A product is visible on a channel only when it has a publication record joining the two. Each publication carries an optional window:++| Publication state | What customers see |+|---|---|+| No publication exists | Product is not on this channel — invisible |+| Publication has no dates set | Live now and indefinitely |+| `published_at` is in the future | Scheduled — not yet visible |+| `unpublished_at` is in the past | Hidden — was visible, now sunset |+| Within the window | Live |++Product status (`draft` / `active` / `archived`) is the **outer gate**: a Draft or Archived product is hidden on every channel regardless of its publication window. The dashboard's Publishing card renders this as a "Not available" badge on every channel row when status isn't `active`.++### Order attribution++Every order is attributed to one channel. The channel is set from the `X-Spree-Channel` header on cart creation, from the merchant's selection on the "New order" form, or defaults to the store's primary channel.++This attribution drives reporting (best-selling by channel, revenue per channel) and per-channel order routing — see [Order Routing](/v5/developer/core-concepts/shipments#order-routing).++### Storefront Access Gating++<Since version="5.6" />++A channel's `storefront_access` decides what an **anonymous** visitor — a request with no authenticated customer — may see. Logged-in customers are never gated. The posture is one of three values:++| Mode | Guest sees catalog | Guest sees prices | Use case |+|---|---|---|---|+| `public` | Yes | Yes | The default. An open storefront — anyone can browse; guests can also check out when `guest_checkout` is enabled. |+| `prices_hidden` | Yes | No — prices come back `null` | A catalog you want discoverable, with pricing revealed only after sign-in (e.g. a trade catalog for lead generation). |+| `login_required` | No — reads rejected with `401` | No | A fully gated surface — a guest can't read the catalog at all (e.g. a members-only or B2B wholesale portal). |++The gate is enforced by the **Store API**, not the storefront, so a storefront app can't loosen it:++- **`login_required`** — every gated read returns `401` for an unauthenticated request. Endpoints that must stay reachable before sign-in (authentication, password reset, reference data like countries and currencies) are exempt.+- **`prices_hidden`** — reads succeed, but every money field is serialized as `null` for a guest. The storefront renders these as a sign-in prompt rather than a price.++A companion control, **`guest_checkout`**, decides whether an order can be placed without an account on the channel. It's independent of `storefront_access` — a `public` channel can still require accounts, and the two are resolved separately.++#### Store fallback++Both controls fall back to the owning [Store](/v5/developer/core-concepts/stores) when the channel's own value is unset — the same inheritance pattern as the channel's order-routing strategy. `storefront_access` resolves to the channel value, then the store value, and finally `public` when neither is set. This lets you set a store-wide default (e.g. "all channels require login") and override per channel where needed.++<CodeGroup>++```typescript Admin SDK+// Gate a channel behind sign-in, and require accounts at checkout+await adminClient.channels.update('ch_wholesale', {+ storefront_access: 'login_required',+ guest_checkout: false,+})++// Clear the channel value to inherit the store's default+await adminClient.channels.update('ch_wholesale', {+ storefront_access: null,+})+```++```bash cURL+curl -X PATCH 'https://api.mystore.com/api/v3/admin/channels/ch_wholesale' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{ "storefront_access": "login_required", "guest_checkout": false }'+```++</CodeGroup>++Switching a channel between modes takes effect immediately — the posture is resolved per request, so no cache warm-up or redeploy is needed. The Next.js storefront's [wholesale portal](/v5/developer/storefront/nextjs/wholesale) is a worked example of a `login_required` / `prices_hidden` channel driving the UI.++## Publishing Products on Channels++### Dashboard++The product edit page has a **Publishing** card with one row per channel the product is on. Click *Manage* to attach or detach channels via checkboxes. Each row expands into a per-channel schedule editor.++Bulk operations from the product list: *Add to sales channels…* and *Remove from sales channels…*.++### Admin API++Three endpoints cover the publishing surface:++| Endpoint | Use case |+|---|---|+| `POST /api/v3/admin/channels/:id/add_products` | Publish one or more products on a specific channel |+| `POST /api/v3/admin/channels/:id/remove_products` | Unpublish products from a specific channel |+| `POST /api/v3/admin/products/bulk_add_to_channels` | Publish many products across many channels in a single request |++<CodeGroup>++```typescript Admin SDK+await adminClient.channels.addProducts('ch_xxx', {+ product_ids: ['prod_aaa', 'prod_bbb'],+ // Optional window — when omitted, existing schedules are preserved+ published_at: '2026-07-01T00:00:00Z',+ unpublished_at: '2026-12-31T23:59:59Z',+})+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/admin/channels/ch_xxx/add_products' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{+ "product_ids": ["prod_aaa", "prod_bbb"],+ "published_at": "2026-07-01T00:00:00Z",+ "unpublished_at": "2026-12-31T23:59:59Z"+ }'+```++</CodeGroup>++`channels.addProducts` is idempotent: re-publishing an already-published product is a no-op for its window unless `published_at` / `unpublished_at` are explicitly passed. Cross-store onboarding is allowed when the caller's key has update permission on the product.++For per-product updates, use `PATCH /api/v3/admin/products/:id` with a `product_publications` array:++<CodeGroup>++```typescript Admin SDK+await adminClient.products.update('prod_xxx', {+ product_publications: [+ { channel_id: 'ch_online' },+ { channel_id: 'ch_pos', published_at: '2026-07-01T00:00:00Z' },+ ],+})+```++```bash cURL+curl -X PATCH 'https://api.mystore.com/api/v3/admin/products/prod_xxx' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{+ "product_publications": [+ { "channel_id": "ch_online" },+ { "channel_id": "ch_pos", "published_at": "2026-07-01T00:00:00Z" }+ ]+ }'+```++</CodeGroup>++The write contract is **full-set**: the array represents the complete desired state. Channels absent from the payload are detached.++## Auto-Publish Behavior++- **Dashboard** — new products are auto-published on the store's default channel. The merchant can untick channels via the Publishing card post-create.+- **Admin API** — new products are **not** auto-published. The caller supplies `product_publications: [{ channel_id }]` on create, or calls `POST /admin/channels/:id/add_products` afterwards.+- **Sample data** (`bin/rake spree:load_sample_data`) — all loaded products are explicitly published on the default channel.++## Related Documentation++- [Stores](/v5/developer/core-concepts/stores) — Channels belong to a store+- [Markets](/v5/developer/core-concepts/markets) — Different from channels: markets segment geography/currency, channels segment selling surfaces+- [Products](/v5/developer/core-concepts/products) — Product catalog and publication+- [Order Routing](/v5/developer/core-concepts/shipments#order-routing) — Channels can override the store's routing strategy+- [Store SDK: Products](/v5/developer/sdk/store/products) — Channel-scoped product listing and filtering+- [Admin SDK: Resources](/v5/developer/sdk/admin/resources) — How `adminClient.channels.addProducts` and other resource methods are structured+- [Wholesale Portal](/v5/developer/storefront/nextjs/wholesale) — A gated channel driving the Next.js storefront's B2B surfacediff --git a/docs/v5/developer/core-concepts/customers.mdx b/docs/v5/developer/core-concepts/customers.mdxnew file mode 100644index 0000000000..2a87fdb44b--- /dev/null+++ b/docs/v5/developer/core-concepts/customers.mdx@@ -0,0 +1,329 @@+---+title: Customers+description: How Spree models customer accounts — registration, authentication, addresses, order history, store credits, and guest checkout behavior.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/customers"+---++import { Since } from '/snippets/since.mdx';++## Overview++Customers interact with your store through the Store API. They can register, log in, manage their profile, and view order history.++```mermaid+erDiagram+ Customer ||--o{ Order : "places"+ Customer ||--o{ Address : "has many"+ Customer ||--o{ Wishlist : "has many"+ Customer ||--o{ StoreCredit : "has many"+ Customer ||--o{ PaymentSource : "has many"++ Customer {+ string id+ string email+ string first_name+ string last_name+ }++ Order {+ string number+ string state+ }++ Address {+ string firstname+ string lastname+ string address1+ string city+ }++ Wishlist {+ string name+ boolean is_default+ }+```++## Registration++<CodeGroup>++```typescript Store SDK+const { token, user } = await client.customers.create({+ email: '[email protected]',+ password: 'password123',+ password_confirmation: 'password123',+ first_name: 'John',+ last_name: 'Doe',+})+// token => JWT token for subsequent authenticated requests+// user => { id: "cus_abc123", email: "[email protected]", first_name: "John", ... }+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/store/customers' \+ -H 'X-Spree-Api-Key: pk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{+ "email": "[email protected]",+ "password": "password123",+ "password_confirmation": "password123",+ "first_name": "John",+ "last_name": "Doe"+ }'+```++</CodeGroup>++<Note>+The Store API flow above is **customer self-registration** — the customer sets a password and gets a JWT back. To [create a customer record from the back office](/v5/developer/sdk/admin/resources) (importers, CRM sync, phone orders), use the [Admin SDK](/v5/developer/sdk/admin/quickstart) instead. No password is set, so it's a managed record rather than a sign-up:++```typescript+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++const customer = await client.customers.create({+ email: '[email protected]',+ first_name: 'John',+ last_name: 'Doe',+ tags: ['wholesale'],+})+```+</Note>++## Login++<CodeGroup>++```typescript Store SDK+const { token, user } = await client.auth.login({+ email: '[email protected]',+ password: 'password123',+})+// Use the token for authenticated requests+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/store/auth/login' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{+ "email": "[email protected]",+ "password": "password123"+ }'+```++</CodeGroup>++The response includes a JWT `token` and a `user` object. Pass the token in subsequent requests via the [`Authorization: Bearer <token>`](/api-reference/store-api/authentication) header.++## Token Refresh++Refresh an expiring token to keep the session alive. For how `client.auth.login` and `client.auth.refresh` fit into configuring the SDK for guest vs customer (JWT) auth, see the [SDK authentication guide](/v5/developer/sdk/authentication):++<CodeGroup>++```typescript Store SDK+const { token, refresh_token } = await client.auth.refresh({+ refresh_token: existingRefreshToken,+})+// Persist the rotated refresh_token for the next refresh+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/store/auth/refresh' \+ -H 'X-Spree-Api-Key: pk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{ "refresh_token": "rt_xxx" }'+```++</CodeGroup>++## Password Reset++Password reset is a two-step flow. First, request a reset email. Then, use the token from the email to set a new password.++### Step 1: Request Reset++<CodeGroup>++```typescript Store SDK+await client.passwordResets.create({+ email: '[email protected]',+ redirect_url: 'https://myshop.com/reset-password',+})+// Always returns { message: "..." } — even if the email doesn't exist+// This prevents email enumeration+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/store/password_resets' \+ -H 'X-Spree-Api-Key: pk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{+ "email": "[email protected]",+ "redirect_url": "https://myshop.com/reset-password"+ }'+```++</CodeGroup>++The optional `redirect_url` parameter specifies where the password reset link in the email should point to. The token will be appended as a query parameter (e.g., `https://myshop.com/reset-password?token=...`). If the store has Allowed Origins configured, the `redirect_url` must match one of them.++This fires a `customer.password_reset_requested` event with the reset token in the payload. If you're using the `spree_emails` package, the email is sent automatically. Otherwise, subscribe to this event to send the reset email yourself (see [Events](/v5/developer/core-concepts/events)).++### Step 2: Reset Password++<CodeGroup>++```typescript Store SDK+const { token, user } = await client.passwordResets.update(+ 'reset-token-from-email',+ {+ password: 'newsecurepassword',+ password_confirmation: 'newsecurepassword',+ }+)+// Returns JWT token + user (auto-login)+```++```bash cURL+curl -X PATCH 'https://api.mystore.com/api/v3/store/password_resets/RESET_TOKEN' \+ -H 'X-Spree-Api-Key: pk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{+ "password": "newsecurepassword",+ "password_confirmation": "newsecurepassword"+ }'+```++</CodeGroup>++On success, the user is automatically logged in and a JWT token is returned. The reset token expires after 15 minutes (configurable via `Spree::Config.customer_password_reset_expires_in`) and is single-use (changing the password invalidates it).++## Newsletter Subscriptions++<Since version="5.5" />++Headless storefronts often need to collect newsletter signups before account creation (footer forms, popup overlays). The Store API exposes a double opt-in subscription flow that mirrors the password reset webhook pattern.++### Step 1: Subscribe++<CodeGroup>++```typescript Store SDK+await client.newsletterSubscribers.create({+ email: '[email protected]',+ redirect_url: 'https://myshop.com/newsletter/confirm',+})+// Returns the NewsletterSubscriber (verified: false for guests)+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/store/newsletter_subscribers' \+ -H 'X-Spree-Api-Key: pk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{+ "email": "[email protected]",+ "redirect_url": "https://myshop.com/newsletter/confirm"+ }'+```++</CodeGroup>++The optional `redirect_url` points at the storefront page that will receive the verification token. It is validated against the store's Allowed Origins — URLs that do not match are silently dropped from the webhook payload (secure-by-default).++This fires a `newsletter_subscriber.subscription_requested` event whose payload includes `email`, `verification_token`, and the validated `redirect_url`. Subscribe to this event from your storefront's webhook handler to send the confirmation email — the link in the email should point to `<redirect_url>?token=<verification_token>`. The bundled `spree_emails` package also listens to this event and sends a default confirmation email if you're not running a headless storefront.++If the request is authenticated via a customer JWT and the JWT's email matches the subscribed email, the subscription is **auto-verified** and no event is fired (the user has already proven email ownership).++### Step 2: Verify++<CodeGroup>++```typescript Store SDK+await client.newsletterSubscribers.verify({+ token: 'token-from-email',+})+// Returns the verified NewsletterSubscriber+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/store/newsletter_subscribers/verify' \+ -H 'X-Spree-Api-Key: pk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{ "token": "token-from-email" }'+```++</CodeGroup>++On success, the subscriber is marked verified. If the subscription is linked to a customer record, that customer's `accepts_email_marketing` flag is also set to `true`. Consent is preserved across registration: if a guest subscribes and later registers with the same email, the existing subscriber is reused — registration won't accidentally reset their opt-in state.++## Customer Profile++<CodeGroup>++```typescript Store SDK+// Get current customer+const customer = await client.customer.get()+// {+// id: "cus_xxx",+// email: "[email protected]",+// first_name: "John",+// last_name: "Doe",+// default_shipping_address: { ... },+// default_billing_address: { ... },+// addresses: [{ ... }, { ... }],+// }++// Update profile+const updated = await client.customer.update({+ first_name: 'Jonathan',+ accepts_email_marketing: true,+})+```++```bash cURL+# Get current customer+curl 'https://api.mystore.com/api/v3/store/customers/me' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'Authorization: Bearer <jwt_token>'++# Update profile+curl -X PATCH 'https://api.mystore.com/api/v3/store/customers/me' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'Authorization: Bearer <jwt_token>' \+ -H 'Content-Type: application/json' \+ -d '{ "first_name": "Jonathan", "accepts_email_marketing": true }'+```++</CodeGroup>++## Customer Resources++Authenticated customers have access to these resources:++| Resource | Description |+|----------|-------------|+| [**Addresses**](/v5/developer/core-concepts/addresses#customer-address-book) | Billing and shipping addresses with default selection |+| [**Orders**](/v5/developer/core-concepts/orders#order-history) | Past order history |+| **Credit Cards** | Saved credit cards for checkout |+| **Payment Sources** | Other saved payment methods (PayPal, Klarna, etc.) |+| **Store Credits** | Balance assigned by the store, usable at checkout |+| **Gift Cards** | Gift cards owned by or assigned to the customer |+| **Wishlists** | Saved product lists |++## Guest Checkout++Customers don't need to register to purchase. Guest checkout uses an order token (`X-Spree-Token`) to identify the cart. See [Orders — Cart](/v5/developer/core-concepts/orders#cart) for details.++## Related Documentation++- [Account (Store SDK)](/v5/developer/sdk/store/account) — Task-oriented walkthrough of registration, login, profile, addresses, and order history+- [Addresses](/v5/developer/core-concepts/addresses) — Customer address management+- [Orders](/v5/developer/core-concepts/orders) — Order history and checkout+- [Authentication](/v5/developer/customization/authentication) — Custom authentication setup+- [Staff & Roles](/v5/developer/core-concepts/staff-roles) — Admin users and permissionsdiff --git a/docs/v5/developer/core-concepts/events.mdx b/docs/v5/developer/core-concepts/events.mdxnew file mode 100644index 0000000000..95e0c1efbe--- /dev/null+++ b/docs/v5/developer/core-concepts/events.mdx@@ -0,0 +1,666 @@+---+title: Events+description: Spree's event system — publish and subscribe to lifecycle events from orders, products, and users to trigger background jobs and integrations.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/events"+---++import { Since } from '/snippets/since.mdx';++<Since version="5.3" />++## Overview++Spree includes a powerful event system that allows you to react to various actions happening in your store. When something happens (an order is completed, a product is created, etc.), Spree publishes an event that your code can subscribe to and handle.++This pattern enables loose coupling between components and makes it easy to:++- Send email notifications when orders are placed+- Sync data with external services when products change+- Log audit trails for compliance+- Trigger webhooks to notify third-party systems+- Update caches when inventory changes++## How Events Work++Spree's event system provides a clean API through:++1. **`Spree::Events`** - The main module for publishing and subscribing to events+2. **`Spree::Subscriber`** - Base class for creating event subscribers+3. **`Spree::Publishable`** - Concern that enables models to publish events++When an event is published, all matching subscribers are notified. By default, subscribers run asynchronously via background jobs to avoid blocking the main request.++```mermaid+flowchart TB+ subgraph Spree Application+ A[Model Action] --> B[publish_event]+ B --> C[Event Serializer]+ C --> D[Spree::Events]+ end++ subgraph Event Adapter+ D --> E[Find Matching Subscribers]+ E --> F{Async?}+ F -->|Yes| G[Queue Background Job]+ F -->|No| H[Execute Immediately]+ end++ subgraph Subscribers+ G --> I[SubscriberJob]+ I --> J[Your Subscriber]+ H --> J+ J --> K[Send Email]+ J --> L[Sync External Service]+ J --> M[Update Cache]+ J --> N[Trigger Webhook]+ end+```++## Creating a Subscriber++The fastest path is the generator — it creates the class, a spec stub, and registers the subscriber in `config/initializers/spree.rb` (the step that's easy to forget):++<CodeGroup>++```bash Spree CLI (Docker)+spree generate subscriber OrderCompleted order.completed+```++```bash Without Spree CLI+bin/rails g spree:subscriber OrderCompleted order.completed+```++</CodeGroup>++Or create the class by hand in `app/subscribers/`, inheriting from `Spree::Subscriber`:++```ruby app/subscribers/order_completed_subscriber.rb+class OrderCompletedSubscriber < Spree::Subscriber+ subscribes_to 'order.completed'++ def handle(event)+ order_id = event.payload['id']+ order = Spree::Order.find_by_prefix_id(order_id)+ return unless order++ # Your custom logic here+ ExternalService.notify_order_placed(order)+ end+end+```++Then register it in an initializer — subscribers are not auto-discovered (see [Registering Subscribers](#registering-subscribers)):++```ruby config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.subscribers << OrderCompletedSubscriber+end+```++### Subscriber DSL++The `Spree::Subscriber` class provides a clean DSL for declaring subscriptions:++```ruby+class MySubscriber < Spree::Subscriber+ # Subscribe to a single event+ subscribes_to 'order.completed'++ # Subscribe to multiple events+ subscribes_to 'order.completed', 'order.canceled', 'order.resumed'++ # Subscribe to all events matching a pattern+ subscribes_to 'order.*' # All order events+ subscribes_to '*.*' # All events (use sparingly!)++ # Run synchronously instead of via background job+ subscribes_to 'order.completed', async: false+end+```++### Handling Multiple Events++When subscribing to multiple events, use the `on` DSL to route events to specific methods:++```ruby app/subscribers/order_audit_subscriber.rb+class OrderAuditSubscriber < Spree::Subscriber+ subscribes_to 'order.completed', 'order.canceled', 'order.resumed'++ on 'order.completed', :log_order_completed+ on 'order.canceled', :log_order_canceled+ on 'order.resumed', :log_order_resumed++ private++ def log_order_completed(event)+ create_audit_log(event, 'completed')+ end++ def log_order_canceled(event)+ create_audit_log(event, 'canceled')+ end++ def log_order_resumed(event)+ create_audit_log(event, 'resumed')+ end++ def create_audit_log(event, action)+ AuditLog.create!(+ resource_type: 'Spree::Order',+ resource_id: event.payload['id'],+ action: action,+ occurred_at: event.created_at+ )+ end+end+```++## Working with Events++### Event Object++When your subscriber receives an event, you get a `Spree::Event` object with:++```ruby+def handle(event)+ event.id # => "550e8400-e29b-41d4-a716-446655440000" (UUID)+ event.name # => "order.completed"+ event.store_id # => 1 (ID of the store where the event originated)+ event.payload # => { "id" => 1, "number" => "R123456", ... }+ event.metadata # => { "spree_version" => "<spree_version>" }+ event.created_at # => Time when event was published++ # Helper methods+ event.store # => Spree::Store instance (lazy loaded)+ event.resource_type # => "order" (extracted from name)+ event.action # => "completed" (extracted from name)+end+```++### Finding the Record++The payload contains serialized attributes, not the actual record. To get the record:++```ruby+def handle(event)+ record_id = event.payload['id']+ record = Spree::Order.find_by_prefix_id(record_id)+ return unless record++ # Work with the record+end+```++<Warning>+For destroy events, the record no longer exists in the database. Use the payload data instead, or capture what you need before deletion.+</Warning>++## Available Events++### Lifecycle Events++Models that include `Spree::Publishable` and call `publishes_lifecycle_events` automatically publish:++| Event Pattern | Description |+|---------------|-------------|+| `{model}.created` | Record was created |+| `{model}.updated` | Record was updated |+| `{model}.deleted` | Record was deleted |++For example, `Spree::Price` publishes `price.created`, `price.updated`, and `price.deleted`.++Models with lifecycle events enabled include: `Order`, `Payment`, `Price`, `Shipment`, `Variant`, `LineItem`, `StockItem`, and many others.++### Order Events++| Event | Description |+|-------|-------------|+| `order.created` | Order was created |+| `order.updated` | Order was updated |+| `order.completed` | Order checkout completed |+| `order.canceled` | Order was canceled |+| `order.resumed` | Canceled order was resumed |+| `order.paid` | Order is fully paid |+| `order.shipped` | All order shipments are shipped |++### Shipment Events++| Event | Description |+|-------|-------------|+| `shipment.created` | Shipment was created |+| `shipment.updated` | Shipment was updated |+| `shipment.shipped` | Shipment was shipped |+| `shipment.canceled` | Shipment was canceled |+| `shipment.resumed` | Shipment was resumed |++### Payment Events++| Event | Description |+|-------|-------------|+| `payment.created` | Payment was created |+| `payment.updated` | Payment was updated |+| `payment.paid` | Payment was completed |++### Price Events++| Event | Description |+|-------|-------------|+| `price.created` | Price was created |+| `price.updated` | Price was updated |+| `price.deleted` | Price was deleted |++### User Events++| Event | Description |+|-------|-------------|+| `user.created` | User was created |+| `user.updated` | User was updated |+| `user.deleted` | User was deleted |++When `Spree.admin_user_class` differs from `Spree.user_class`, admin users publish the equivalent `admin.*` events (see the Admin Events table below).++### Admin Events++| Event | Description |+|-------|-------------|+| `admin.created` | Admin user was created |+| `admin.updated` | Admin user was updated |+| `admin.deleted` | Admin user was deleted |++### Product Events++| Event | Description |+|-------|-------------|+| `product.activated` | Product status changed to active |+| `product.archived` | Product status changed to archived |+| `product.out_of_stock` | Product has no stock left for any variant |+| `product.back_in_stock` | Product was out of stock and now has stock again |++## Publishing Custom Events++You can publish custom events from anywhere in your application:++### From a Model++Models including `Spree::Publishable` can use `publish_event`:++```ruby+class Spree::Order < Spree.base_class+ def mark_as_fraudulent!+ update!(fraudulent: true)+ publish_event('order.marked_fraudulent')+ end+end+```++### From Anywhere++Use `Spree::Events.publish` directly:++```ruby+Spree::Events.publish(+ 'inventory.low_stock',+ { variant_id: variant.id, quantity: variant.total_on_hand }+)+```++## Event Serializers++Event payloads are generated using the same [Store API V3 serializers](/api-reference/store-api/introduction) used by the REST API. This means webhook payloads and API responses share the same schema, making it easy to reuse types in your integrations.++### How Serializers Work++When a model publishes an event, Spree looks for a V3 serializer class matching the model name:++- `Spree::Order` → `Spree::Api::V3::OrderSerializer`+- `Spree::Product` → `Spree::Api::V3::ProductSerializer`+- `Spree::Payment` → `Spree::Api::V3::PaymentSerializer`++For STI models (e.g., `Spree::Exports::Products`), the serializer lookup walks up the class hierarchy until it finds a match (e.g., → `Spree::Api::V3::ExportSerializer`).++If no serializer is found, a minimal fallback payload is returned:++```json+{ "id": "prod_86Rf07xd4z", "created_at": "2025-01-15T10:00:00Z", "updated_at": "2025-01-15T10:30:00Z" }+```++### Built-in Serializers++Spree includes V3 serializers for all core models in [`api/app/serializers/spree/api/v3/`](https://github.com/spree/spree/tree/main/api/app/serializers/spree/api/v3):++| Serializer | Model |+|------------|-------|+| `OrderSerializer` | Orders with totals, statuses, nested line items, fulfillments, payments, addresses |+| `ProductSerializer` | Products with pricing, stock status, availability |+| `PaymentSerializer` | Payments with amounts, states, nested payment method and source |+| `FulfillmentSerializer` | Fulfillments (shipments) with tracking, nested delivery method and delivery rates |+| `LineItemSerializer` | Line items with quantity, pricing, nested option values |+| `VariantSerializer` | Variants with SKU, pricing, nested option values |+| `PriceSerializer` | Prices with amounts, currency, price list |+| ... | [And many more](https://github.com/spree/spree/tree/main/api/app/serializers/spree/api/v3) |++### Payload Context++Event serializers receive specific context parameters that control what data is included:++- **`store`** — Prefers the resource's store (e.g., `order.store`), falls back to `Spree::Current.store`+- **`currency`** — Uses `Spree::Current.currency` (with full fallback chain)+- **`user: nil`** — Events never include user-specific pricing+- **`includes: []`** — Conditional associations are not included in event payloads++This means event payloads contain the same top-level attributes and unconditional associations as API responses, but conditional associations (like product variants, media, or custom fields) are excluded.++### Overriding Event Serializers++To customize the payload for existing events, create a custom V3 serializer and configure it via [dependencies](/v5/developer/customization/dependencies):++```ruby app/serializers/my_app/order_serializer.rb+module MyApp+ class OrderSerializer < Spree::Api::V3::OrderSerializer+ # Add custom attributes+ attribute :loyalty_points do |order|+ (order.total.to_f * 10).to_i+ end++ attribute :custom_field do |order|+ order.custom_field+ end+ end+end+```++```ruby config/initializers/spree.rb+Spree.api.order_serializer = 'MyApp::OrderSerializer'+```++<Warning>+When overriding serializers, make sure to include all attributes that webhooks and subscribers depend on. Removing attributes may break integrations.+</Warning>++### Serializers for Custom Models++If you add a custom model that publishes events, create a V3 serializer:++```ruby app/models/spree/subscription.rb+module Spree+ class Subscription < Spree.base_class+ publishes_lifecycle_events++ def renew!+ update!(renewed_at: Time.current)+ publish_event('subscription.renewed')+ end+ end+end+```++```ruby app/serializers/spree/api/v3/subscription_serializer.rb+module Spree+ module Api+ module V3+ class SubscriptionSerializer < BaseSerializer+ typelize plan_name: :string, status: :string,+ user_id: [:string, nullable: true],+ renewed_at: [:string, nullable: true],+ expires_at: [:string, nullable: true]++ attributes :plan_name, :status,+ renewed_at: :iso8601, expires_at: :iso8601,+ created_at: :iso8601, updated_at: :iso8601++ attribute :user_id do |subscription|+ subscription.user&.prefixed_id+ end+ end+ end+ end+end+```++Models without a matching serializer will use a minimal fallback payload containing only `id`, `created_at`, and `updated_at`.++## Registering Subscribers++Subscribers are not auto-discovered — every subscriber must be registered explicitly, regardless of where the class lives. Add it to the `Spree.subscribers` array in `config/initializers/spree.rb` (or any initializer):++```ruby config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.subscribers << CustomSubscriber+end+```++To remove a built-in subscriber:++```ruby config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.subscribers.delete(Spree::ExportSubscriber)+end+```++## Synchronous vs Asynchronous++By default, subscribers run asynchronously via a background job. This prevents slow subscriber code from blocking HTTP requests.++For critical operations that must complete before the request finishes, use synchronous mode:++```ruby+class CriticalOrderHandler < Spree::Subscriber+ subscribes_to 'order.completed', async: false++ def handle(event)+ # This runs immediately, blocking the request+ end+end+```++<Warning>+Use synchronous subscribers sparingly. They can significantly slow down your application if the handler code is slow or makes external API calls.+</Warning>++## Temporarily Disabling Events++You can disable event publishing temporarily:++```ruby+Spree::Events.disable do+ # Events published in this block won't trigger subscribers+ order.complete!+end+```++This is useful for:+- Data migrations where you don't want to trigger side effects+- Test setup where subscribers would interfere+- Bulk operations where individual events would be too noisy++## Testing Subscribers++### Testing Event Handling++```ruby spec/subscribers/order_completed_subscriber_spec.rb+require 'spec_helper'++RSpec.describe OrderCompletedSubscriber do+ let(:order) { create(:completed_order_with_totals) }+ let(:event) do+ Spree::Event.new(+ name: 'order.completed',+ payload: order.event_payload+ )+ end++ describe '#handle' do+ it 'notifies external service' do+ expect(ExternalService).to receive(:notify_order_placed).with(order)+ described_class.new.handle(event)+ end+ end+end+```++### Testing Event Publishing++Stub `Spree::Events.publish` to assert an event is published:++```ruby+it 'publishes order.completed event' do+ expect(Spree::Events).to receive(:publish).with(+ 'order.completed',+ hash_including('id' => order.id)+ )++ order.complete!+end+```++The `lifecycle events` shared examples in `spree/core/lib/spree/testing_support/lifecycle_events.rb` cover the standard `created`/`updated`/`deleted` lifecycle events.++## Best Practices++<CardGroup cols={2}>+ <Card title="Keep handlers fast" icon="bolt">+ Move slow operations to background jobs. Subscribers should do minimal work and delegate heavy lifting.+ </Card>++ <Card title="Handle missing records" icon="shield">+ Always check if the record exists before processing. It may have been deleted between event publish and handler execution.+ </Card>++ <Card title="Be idempotent" icon="rotate">+ Design handlers to be safely re-run. Events might be delivered more than once in edge cases.+ </Card>++ <Card title="Use specific patterns" icon="crosshairs">+ Subscribe to specific events rather than wildcards when possible. This makes code easier to understand and debug.+ </Card>+</CardGroup>++## Example: Inventory Alert Subscriber++Here's a complete example of a subscriber that sends alerts when inventory is low:++```ruby app/subscribers/inventory_alert_subscriber.rb+class InventoryAlertSubscriber < Spree::Subscriber+ subscribes_to 'stock_item.updated'++ LOW_STOCK_THRESHOLD = 10++ def handle(event)+ stock_item = find_stock_item(event)+ return unless stock_item+ return unless low_stock?(event)++ send_low_stock_alert(stock_item)+ end++ private++ def find_stock_item(event)+ Spree::StockItem.find_by_prefix_id(event.payload['id'])+ end++ def low_stock?(event)+ event.payload['count_on_hand'].to_i < LOW_STOCK_THRESHOLD+ end++ def send_low_stock_alert(stock_item)+ InventoryMailer.low_stock_alert(+ variant: stock_item.variant,+ stock_location: stock_item.stock_location,+ count_on_hand: stock_item.count_on_hand+ ).deliver_later+ end+end+```++<Note>+A lifecycle event payload carries only the resource's current serialized state, not its previous values. If you need a true "just dropped below the threshold" check that compares the count before and after the change, record or cache the prior count separately rather than reading it from the event payload.+</Note>++## Custom Event Adapters++Spree's event system uses an adapter pattern, making it possible to swap the underlying event infrastructure. By default, Spree uses [`ActiveSupport::Notifications`](https://api.rubyonrails.org/classes/ActiveSupport/Notifications.html), but you can create custom adapters for other backends like Kafka, RabbitMQ, or Redis Pub/Sub.++### Configuring a Custom Adapter++Set your adapter class in an initializer:++```ruby config/initializers/spree.rb+Spree.events_adapter_class = 'MyApp::Events::KafkaAdapter'+```++### Creating a Custom Adapter++Inherit from `Spree::Events::Adapters::Base` and implement the required methods:++```ruby app/models/my_app/events/kafka_adapter.rb+module MyApp+ module Events+ class KafkaAdapter < Spree::Events::Adapters::Base+ def publish(event_name, payload, metadata = {})+ event = build_event(event_name, payload, metadata)++ # Publish to Kafka+ kafka_producer.produce(+ event.to_json,+ topic: "spree.#{event_name}"+ )++ event+ end++ def subscribe(pattern, subscriber, options = {})+ registry.register(pattern, subscriber, options)+ end++ def unsubscribe(pattern, subscriber)+ registry.unregister(pattern, subscriber)+ end++ def activate!+ @kafka_producer = Kafka.new(+ seed_brokers: ENV['KAFKA_BROKERS']+ ).producer+ end++ def deactivate!+ @kafka_producer&.shutdown+ end++ private++ attr_reader :kafka_producer+ end+ end+end+```++### Base Class Interface++The `Spree::Events::Adapters::Base` class defines the required interface:++| Method | Description |+|--------|-------------|+| `publish(event_name, payload, metadata)` | Publish an event, return `Spree::Event` |+| `subscribe(pattern, subscriber, options)` | Register a subscriber for a pattern |+| `unsubscribe(pattern, subscriber)` | Remove a subscriber |+| `activate!` | Called during application initialization |+| `deactivate!` | Called during shutdown |++The base class also provides helper methods:+- `build_event(name, payload, metadata)` - Creates a `Spree::Event` instance+- `invoke_subscribers(event)` - Finds and invokes matching subscribers (internally calling `registry.subscriptions_for`)+- `registry` - Access to the `Spree::Events::Registry` instance++<Info>+See `Spree::Events::Adapters::ActiveSupportNotifications` for a complete reference implementation.+</Info>++## Related Documentation++- [Events Tutorial](/v5/developer/tutorial/events) - Hands-on, step-by-step walkthrough of building an event subscriber+- [Webhooks](/v5/developer/core-concepts/webhooks) - HTTP callbacks for external integrations+- [Webhooks & Events Reference](/api-reference/webhooks-events) - Catalog of event and webhook payloads+- [Customization Quickstart](/v5/developer/customization/quickstart) - Overview of all customization options+- [Decorators](/v5/developer/customization/decorators) - When to use decorators vs events+- [Checkout Flow](/v5/developer/customization/checkout) - Using events in checkout customizationdiff --git a/docs/v6/developer/core-concepts/imports-exports.mdx b/docs/v5/developer/core-concepts/imports-exports.mdxsimilarity index 96%rename from docs/v6/developer/core-concepts/imports-exports.mdxrename to docs/v5/developer/core-concepts/imports-exports.mdxindex 7bbc54dd0a..40c992e130 100644--- a/docs/v6/developer/core-concepts/imports-exports.mdx+++ b/docs/v5/developer/core-concepts/imports-exports.mdx@@ -1,5 +1,6 @@---title: Imports & Exports+canonical: "https://spreecommerce.org/docs/developer/core-concepts/imports-exports"---## Overview@@ -270,12 +271,24 @@ module Spreehas_many :mappings # Field mappingshas_many :rows # CSV rows to process- # Statuses. Each move between them is a workflow — Spree::Imports::- # StartMapping, CompleteMapping, StartProcessing, Complete and- # RetryFailedRows — so every step of the pipeline can be hooked.- include Spree::HasStatus- has_status :pending, :mapping, :completed_mapping, :processing, :completed, :failed,- default: :pending+ # State machine+ state_machine initial: :pending do+ event :start_mapping do+ transition to: :mapping+ end+ event :complete_mapping do+ transition from: :mapping, to: :completed_mapping+ end+ event :start_processing do+ transition from: :completed_mapping, to: :processing+ end+ event :complete do+ transition from: :processing, to: :completed+ end+ event :fail do+ transition to: :failed+ end+ end# Key methodsdef import_schema # Returns schema class instance@@ -738,4 +751,4 @@ Records are filtered by `current_ability` ensuring users only export data they h## Related Documentation- [Admin imports/exports endpoints](/api-reference/admin-api/endpoints) — REST routes and required scopes to trigger imports and exports programmatically.-- [Admin SDK resources](/developer/sdk/admin/resources) — typed TypeScript client for driving these back-office operations.+- [Admin SDK resources](/v5/developer/sdk/admin/resources) — typed TypeScript client for driving these back-office operations.diff --git a/docs/v5/developer/core-concepts/inventory.mdx b/docs/v5/developer/core-concepts/inventory.mdxnew file mode 100644index 0000000000..42e832e66c--- /dev/null+++ b/docs/v5/developer/core-concepts/inventory.mdx@@ -0,0 +1,336 @@+---+title: Inventory+description: Stock locations, stock items, stock movements, and inventory tracking+canonical: "https://spreecommerce.org/docs/developer/core-concepts/inventory"+---++import { Since } from '/snippets/since.mdx';++## Overview++Each [Variant](/v5/developer/core-concepts/products#variants) has a `StockItem` that tracks its inventory at a specific location. A variant can have multiple stock items if it's available at multiple stock locations.++When products are sold or returned, individual `InventoryUnit` records track each unit through the fulfillment process.++Adding new inventory to an out-of-stock product that has backorders will first fill the backorders, then update the available count with the remainder.++During checkout, Spree holds stock with time-limited [Stock Reservations](#stock-reservations) to prevent two customers from buying the same last unit simultaneously.++### Inventory Model Diagram++```mermaid+erDiagram+ StockLocation {+ string name+ string admin_name+ boolean active+ boolean default+ boolean backorderable_default+ boolean propagate_all_variants+ }++ StockItem {+ integer count_on_hand+ boolean backorderable+ integer stock_location_id+ integer variant_id+ }++ StockMovement {+ integer quantity+ string originator_type+ integer originator_id+ integer stock_item_id+ }++ StockTransfer {+ string number+ string reference+ integer source_location_id+ integer destination_location_id+ }++ InventoryUnit {+ string state+ integer variant_id+ integer order_id+ integer shipment_id+ }++ StockReservation {+ integer quantity+ datetime expires_at+ integer stock_item_id+ integer line_item_id+ integer order_id+ }++ StockLocation ||--o{ StockItem : "has many"+ StockLocation ||--o{ StockTransfer : "source"+ StockLocation ||--o{ StockTransfer : "destination"+ Variant ||--o{ StockItem : "has many"+ Variant ||--o{ InventoryUnit : "has many"+ StockItem ||--o{ StockMovement : "has many"+ StockItem ||--o{ StockReservation : "has many"+ StockTransfer ||--o{ StockMovement : "has many"+ Order ||--o{ InventoryUnit : "has many"+ Order ||--o{ StockReservation : "has many"+ Shipment ||--o{ InventoryUnit : "has many"+```++**Key relationships:**+- **Stock Location** → Contains Stock Items (inventory per variant) and is the source/destination for Stock Transfers+- **Stock Item** → Tracks quantity (`count_on_hand`) for a specific Variant at a specific Stock Location+- **Stock Movement** → Records changes to Stock Item quantities (purchases, returns, transfers)+- **Stock Transfer** → Moves inventory between Stock Locations, creating Stock Movements at source and destination+- **Inventory Unit** → Represents individual units in [Orders](/v5/developer/core-concepts/orders) and [Shipments](/v5/developer/core-concepts/shipments)+- **Stock Reservation** → Time-limited soft hold on a Stock Item during checkout, scoped to a specific Order and Line Item++## Inventory Management++### Stock Locations++Stock Locations are the physical locations where your inventory is stored and shipped from.++Stock Locations can be created in the Admin Panel under **Settings → Stock Locations**, or via the Admin API.++Stock Locations have several attributes that define their properties and behavior within the Spree system. Below is a table outlining these attributes:++| Attribute | Description | Example Value |+|-------------------|-----------------------------------------------------------------------------|---------------------|+| `name` | The public name of the stock location. This is returned in Store API | Warehouse 1 |+| `admin_name` | The name used internally for the stock location. This is only returned in Admin API. | WH1 Domestic |+| `address1` | The primary address line for the stock location. | 5th avenue |+| `address2` | The secondary address line for the stock location. | Suite 100 |+| `city` | The city where the stock location is based. | New York |+| `state_id` | The ID of the state where the stock location is based. This references the `State` model. | 1 |+| `country_id` | The ID of the country where the stock location is based. This references the `Country` model. | 1 |+| `zipcode` | The postal code for the stock location. | 10001 |+| `phone` | The contact phone number for the stock location. | 555-1234 |+| `active` | A boolean indicating whether the stock location is active. Inactive stock locations will not be used in stock calculations or be available for selection during checkout. | `true` |+| `default` | A boolean indicating whether the stock location is the default one used for new inventory operations. | `false` |+| `backorderable_default` | A boolean indicating whether new stock items in this location are backorderable by default. | `false` |+| `propagate_all_variants` | A boolean indicating whether new stock items should be automatically created for all Store variants when a new stock location is added. | `false` |++Stock Locations can be easily used for tracking warehouses and other physical locations. They can be used to track separate sections of a warehouse (e.g. aisles, shelves, etc.) or to track different warehouses.++You can easily use them with your Point of Sale (POS) system to track inventory at different locations.++Create and manage stock locations via the [Admin API](/api-reference/admin-api/introduction):++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++const location = await client.stockLocations.create({+ name: 'Warehouse 1',+ admin_name: 'WH1 Domestic',+ default: true,+ country_iso: 'US',+ propagate_all_variants: true,+})++await client.stockLocations.update('sloc_xxx', { active: false })+```++```bash CLI+spree api post /stock_locations -d '{+ "name": "Warehouse 1",+ "default": true,+ "country_iso": "US",+ "propagate_all_variants": true+}'+```++</CodeGroup>++### Stock Items++Stock Items represent the inventory at a stock location for a specific variant. Stock item count on hand can be increased or decreased by creating stock movements.++| Attribute | Description | Example Value |+|-------------------|-----------------------------------------------------------------------------|---------------------|+| `stock_location_id` | References the stock location where the stock item belongs. | `1` |+| `variant_id` | References the variant associated with the stock item. | `32` |+| `count_on_hand` | The number of items available on hand. | `150` |+| `backorderable` | Indicates whether the stock item can be backordered. | `true` |++Stock items are created automatically — for all variants when a location has `propagate_all_variants`, or via a variant's `stock_items` on create. To adjust quantity or backorderable status, **update** the existing stock item via the Admin API. The example below uses a Ransack predicate (`stock_location_id_eq`) to [list a location's stock items](/api-reference/admin-api/querying) before updating one:++<CodeGroup>++```typescript Admin SDK+// List a location's stock items, then adjust one+const { data: items } = await client.stockItems.list({ stock_location_id_eq: 'sloc_xxx' })++await client.stockItems.update('si_xxx', {+ count_on_hand: 150,+ backorderable: true,+})+```++```bash CLI+spree api get /stock_items -q stock_location_id_eq=sloc_xxx+spree api patch /stock_items/si_xxx -d '{"count_on_hand": 150, "backorderable": true}'+```++</CodeGroup>++### Stock Transfers++Stock transfers allow you to move inventory in bulk from one stock location to another stock location. This is handy when you want to integrate with a POS system or other inventory management system. Or you can just rely on Spree being the source of truth for your inventory.++<Info>+Stock Transfers can be created in the Admin dashboard or via the Admin API.+</Info>++Here's the list of attributes for the Stock Transfer model:++| Attribute | Description | Example Value |+|--------------------------|-----------------------------------------------------------------------------|---------------------|+| `number` | The unique number identifier for the stock transfer, generated automatically. | `T123456789` |+| `reference` | An optional reference field for the stock transfer. | Transfer for Event |+| `source_location_id` | The ID of the stock location where the stock is transferred from. | `2` |+| `destination_location_id`| The ID of the stock location where the stock is transferred to. | `3` |++Create a transfer via the [Admin API](/api-reference/admin-api/introduction), listing the variants and quantities to move. Omit `source_location_id` to record an incoming receipt from a vendor:++<CodeGroup>++```typescript Admin SDK+const transfer = await client.stockTransfers.create({+ source_location_id: 'sloc_warehouse',+ destination_location_id: 'sloc_store',+ reference: 'Transfer for Event',+ variants: [+ { variant_id: 'variant_xxx', quantity: 20 },+ { variant_id: 'variant_yyy', quantity: 5 },+ ],+})+```++```bash CLI+spree api post /stock_transfers -d '{+ "source_location_id": "sloc_warehouse",+ "destination_location_id": "sloc_store",+ "variants": [{ "variant_id": "variant_xxx", "quantity": 20 }]+}'+```++</CodeGroup>++Stock transfers are crucial for managing inventory across multiple locations, ensuring that stock levels are accurate and up-to-date.++Each Stock Transfer will hold a list of Stock Movements.++### Stock Movements++Stock Movements track the movement of the inventory:++* when you move inventory between stock locations (via Stock Transfer)+* when you add inventory to a stock location+* when you remove inventory from a stock location+* when customers purchase products+* when customers return products++Here's the list of attributes for the Stock Movement model:++| Attribute | Description | Example Value |+|-------------------|-----------------------------------------------------------------------------|---------------------|+| `stock_item_id` | References the stock item that the movement belongs to. | `45` |+| `quantity` | The quantity by which the stock item's count on hand is changed. Positive values indicate stock being added, while negative values indicate stock being removed. | `-10` |+| `originator_type` | The type of the originator of the stock movement. This is a polymorphic association. | `Spree::Shipment` |+| `originator_id` | The ID of the originator of the stock movement. This is used in conjunction with `originator_type`. | `2` |++Stock Movements are crucial for maintaining accurate inventory levels and for historical tracking of inventory adjustments.++## Stock Reservations <Since version="5.5" />++Stock Reservations are a time-limited soft hold on stock during checkout. When a customer enters checkout, Spree holds the items in their cart for a limited time so other shoppers see reduced availability immediately. Two customers can no longer both pass the availability check on the same last unit only to have one of them fail at order completion.++### What changes for the storefront++Availability now subtracts the units other customers are holding in active checkouts. Whenever you read whether a variant is in stock — whether for a product page, cart line, or checkout summary — Spree returns the post-reservation number automatically. There's nothing for the storefront to compute and physical stock counts on each `StockItem` are never modified by reservations; reservations are an independent layer that's consulted at read time and cleaned up by background jobs.++### Lifecycle++| Trigger | Action |+|---|---|+| Customer enters checkout | A reservation is created for each line item with an expiry timestamp |+| Customer continues mutating the cart while in checkout | The expiry is pushed forward |+| Customer completes the order | The reservation is released; physical stock is decremented as before |+| Customer empties or abandons the cart | The reservation is released or expires automatically |++Reservations attach to each line item; when a line item or order is removed, the reservation goes with it.++### Configuration++| Setting | Default | Purpose |+|---|---|---|+| `Spree::Config[:stock_reservations_enabled]` | `true` | Global kill switch. When `false`, reservations are not created and availability ignores them — behavior matches pre-5.5. |+| `Spree::Config[:default_stock_reservation_ttl_minutes]` | `10` | Fallback hold duration when a Store doesn't override. |+| `store.preferred_stock_reservation_ttl_minutes` | `10` | Per-Store override. Falls back to the global default only when explicitly unset/blank. |++TTL is a Store-level setting — it's a checkout-experience policy, not a warehouse property. A multi-location cart never has to merge conflicting TTLs from different warehouses.++### Insufficient stock during checkout++When a cart change in checkout would push the order beyond available stock, the change is rejected up front. The customer sees a validation error immediately, instead of progressing through payment only to fail at the final submit.++### Background expiry++Abandoned checkouts leave behind expired reservation rows. Spree provides a job to clean them up but does **not** auto-schedule it — your application's job runner needs to invoke it periodically (every minute is typical). See the [5.4 to 5.5 upgrade guide](/v5/developer/upgrades/5.4-to-5.5#schedule-the-stock-reservations-expiry-job) for sidekiq-cron, solid_queue, and good_job snippets.++### Backorderable items++If a stock item is marked backorderable, it represents unlimited supply, so reservations are skipped entirely for that item. Availability is unaffected.++## Inventory Units++As we mentioned above, back-ordered, sold, or shipped products are stored as individual `InventoryUnit` objects so they can have relevant information attached to them.++We create `InventoryUnit` objects when:++* a product is sold (they are added to the Shipment)+* a product is returned++Here's a list of attributes for the Inventory Unit model:++| Attribute | Description | Example Value |+|-------------------|-----------------------------------------------------------------------------|---------------------|+| `variant_id` | References the variant associated with the inventory unit. | `32` |+| `order_id` | References the order associated with the inventory unit. | `123` |+| `shipment_id` | References the shipment associated with the inventory unit. | `77` |+| `state` | The state of the inventory unit | `on_hand` |++Inventory Units states are:++* `on_hand` - the inventory unit is on hand+* `backordered` - the inventory unit is backordered+* `shipped` - the inventory unit is shipped+* `returned` - the inventory unit has been returned++<Note>+As we noted before, when you add new Stock Items to a Variant (eg. via Admin Panel or Admin API), the first Inventory Units to fulfill are the backordered ones.+</Note>++## Disabling Inventory Tracking++If you don't need to track inventory, you can disable it:++- **Per variant** — set `track_inventory` to `false` on a specific variant via the Admin Panel or Admin API+- **Globally** — disable inventory tracking for the entire store in your Spree configuration++## Related Documentation++- [Products](/v5/developer/core-concepts/products) - Product and variant management+- [Shipments](/v5/developer/core-concepts/shipments) - How inventory relates to shipments+- [Orders](/v5/developer/core-concepts/orders) - How inventory is allocated to orders+- [Admin SDK resources](/v5/developer/sdk/admin/resources) - `stockLocations`, `stockItems`, and `stockTransfers` methods used in the examples above+- [Admin API authentication](/api-reference/admin-api/authentication) - How to obtain and scope the secret key (`sk_xxx`) used by these callsdiff --git a/docs/v5/developer/core-concepts/markets.mdx b/docs/v5/developer/core-concepts/markets.mdxnew file mode 100644index 0000000000..b9330188f5--- /dev/null+++ b/docs/v5/developer/core-concepts/markets.mdx@@ -0,0 +1,312 @@+---+title: Markets+description: Configure Spree Markets to bundle geography, currency, and locale into distinct selling regions and run multi-region commerce from a single store.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/markets"+---++import { Since } from '/snippets/since.mdx';++<Since version="5.4" />++## Overview++Markets let you segment a single [Store](/v5/developer/core-concepts/stores) into distinct geographic regions, each with its own currency, locale, and set of countries. For example, an international store might define:++- **North America** — USD, English, ships to US and Canada+- **Europe** — EUR, German, ships to DE, FR, AT, NL+- **United Kingdom** — GBP, English, ships to GB++```mermaid+erDiagram+ Store ||--o{ Market : "has many"+ Market ||--o{ MarketCountry : "has many"+ MarketCountry }o--|| Country : "belongs to"++ Store {+ string name+ string url+ }++ Market {+ string name+ string currency+ string default_locale+ string supported_locales+ boolean tax_inclusive+ boolean default+ }++ Country {+ string iso+ string name+ }+```++## Market Attributes++| Attribute | Description | Example |+|-----------|-------------|---------|+| `name` | Human-readable name, unique per store | `North America` |+| `currency` | ISO 4217 currency code | `USD` |+| `default_locale` | Default language for this market | `en` |+| `supported_locales` | All locales available in this market | `["en", "es"]` |+| `tax_inclusive` | Whether prices include tax (affects display and checkout calculation) | `false` |+| `default` | Whether this is the fallback market when no country match is found | `true` |+| `countries` | List of countries in this market | `[{ iso: "US" }, { iso: "CA" }]` |++## How Markets Work++When a customer visits your store, their country determines which market applies. The market then sets the currency, locale, and tax behavior for that session.++```+Customer's Country → Market → Currency + Locale + Tax Zone+```++The resolution chain:++1. Customer's country is detected (from URL, geolocation, `X-Spree-Country` header, or manual selection)+2. Spree finds the market containing that country+3. The market's currency and locale become the defaults for the session+4. The market's tax zone determines whether prices are shown with or without tax++If no market matches the customer's country, the store's **default market** is used.++## Listing Markets++Fetch all markets for the current store, including their countries:++<CodeGroup>++```typescript Store SDK+const { data: markets } = await client.markets.list()+// [+// {+// id: "mkt_k5nR8xLq",+// name: "North America",+// currency: "USD",+// default_locale: "en",+// supported_locales: ["en", "es"],+// tax_inclusive: false,+// default: true,+// countries: [+// { iso: "US", name: "United States", states_required: true, zipcode_required: true },+// { iso: "CA", name: "Canada", states_required: true, zipcode_required: true }+// ]+// },+// ...+// ]+```++```typescript Admin SDK+const { data: markets } = await adminClient.markets.list()+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/markets' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++## Resolving a Market by Country++When you know a customer's country (e.g., from geolocation or a country picker), resolve which market applies:++<CodeGroup>++```typescript Store SDK+const market = await client.markets.resolve('DE')+// { id: "mkt_gbHJdmfr", name: "Europe", currency: "EUR", tax_inclusive: true, ... }+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/markets/resolve?country=DE' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++Returns the market object on success, or `404` if no market contains that country.++This is useful for building a country switcher — resolve the market to show the customer what currency and language they'll get.++## Countries in a Market++List countries belonging to a specific market. Useful for populating address form dropdowns during checkout:++<CodeGroup>++```typescript Store SDK+const { data: countries } = await client.markets.countries.list('mkt_k5nR8xLq')+// [+// { iso: "CA", name: "Canada", states_required: true, zipcode_required: true },+// { iso: "US", name: "United States", states_required: true, zipcode_required: true }+// ]++// Get a country with its states (for address form dropdowns)+const usa = await client.markets.countries.get('mkt_k5nR8xLq', 'US', {+ expand: ['states'],+})+```++```bash cURL+# List countries in a market+curl 'https://api.mystore.com/api/v3/store/markets/mkt_k5nR8xLq/countries' \+ -H 'X-Spree-API-Key: pk_xxx'++# Get a country with its states+curl 'https://api.mystore.com/api/v3/store/markets/mkt_k5nR8xLq/countries/US?expand=states' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++You can also fetch countries flat (across all markets) or include the market on a country:++<CodeGroup>++```typescript Store SDK+// All countries across all markets+const { data: countries } = await client.countries.list()++// Get a country with its market details+const germany = await client.countries.get('DE', { expand: ['market'] })+// { iso: "DE", name: "Germany", market: { currency: "EUR", default_locale: "de", tax_inclusive: true } }+```++```typescript Admin SDK+const { data: countries } = await adminClient.countries.list()++const germany = await adminClient.countries.get('DE')+```++```bash cURL+# All countries across all markets+curl 'https://api.mystore.com/api/v3/store/countries' \+ -H 'X-Spree-API-Key: pk_xxx'++# Get a country with its market+curl 'https://api.mystore.com/api/v3/store/countries/DE?expand=market' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++## Currency and Locale++Each market defines a [currency and set of supported locales](/api-reference/store-api/monetary-amounts). When a market is resolved, its currency and locale become the defaults for the session.++You can discover all available currencies and locales (aggregated from all markets) via dedicated endpoints:++<CodeGroup>++```typescript Store SDK+const { data: currencies } = await client.currencies.list()+// [{ iso_code: "USD", name: "US Dollar", symbol: "$" }, { iso_code: "EUR", name: "Euro", symbol: "€" }]++const { data: locales } = await client.locales.list()+// [{ code: "en", name: "English" }, { code: "de", name: "German" }]+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/currencies' \+ -H 'X-Spree-API-Key: pk_xxx'++curl 'https://api.mystore.com/api/v3/store/locales' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++See [Localization](/api-reference/store-api/localization) for details on how to pass locale, currency, and country headers in API requests.++## Tax Behavior++The `tax_inclusive` flag on a market controls how prices are displayed and calculated:++- **`tax_inclusive: true`** (common in Europe) — the price shown to the customer already includes tax+- **`tax_inclusive: false`** (common in the US) — tax is added at checkout on top of the displayed price++Each market also resolves a **tax zone** from its default country. This zone determines which tax rates apply when browsing products — before the customer enters a shipping address. Once the customer provides an address at checkout, the actual shipping address takes over for tax calculation.++See [Taxes](/v5/developer/core-concepts/taxes) for details on tax zones and rates.++## Pricing Integration++Markets integrate with the [Pricing](/v5/developer/core-concepts/pricing) system, enabling market-specific pricing through **Price Lists** with a **Market Rule**. This lets you set different prices for the same product in different markets — beyond just currency conversion.++For example, you could price a product at $29.99 in North America and €24.99 in Europe, rather than relying on exchange rate conversion.++See [Pricing — Price Rules](/v5/developer/core-concepts/pricing#price-rules) for details on configuring market-specific price lists.++## Setting Up Markets++Markets are managed in the admin dashboard under **Settings → Markets**. When you run `rails db:seed`, Spree automatically creates a default market for each store.++To create markets programmatically, use the [Admin API](/api-reference/admin-api/introduction). See the [Admin API endpoints](/api-reference/admin-api/endpoints) for the full list of `/markets` routes and required scopes:++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++// North America market (countries by ISO code)+const northAmerica = await client.markets.create({+ name: 'North America',+ currency: 'USD',+ default_locale: 'en',+ country_isos: ['US', 'CA'],+ default: true,+})++// Europe market with tax-inclusive pricing+const europe = await client.markets.create({+ name: 'Europe',+ currency: 'EUR',+ default_locale: 'de',+ supported_locales: ['de', 'en', 'fr'],+ tax_inclusive: true,+ country_isos: ['DE', 'FR', 'AT', 'NL'],+})+```++```bash CLI+spree api post /markets -d '{+ "name": "North America",+ "currency": "USD",+ "default_locale": "en",+ "country_isos": ["US", "CA"],+ "default": true+}'+```++</CodeGroup>++Update or remove a market the same way:++<CodeGroup>++```typescript Admin SDK+await client.markets.update('market_xxx', { tax_inclusive: true })+await client.markets.delete('market_xxx')+```++```bash CLI+spree api patch /markets/market_xxx -d '{"tax_inclusive": true}'+spree api delete /markets/market_xxx+```++</CodeGroup>++## Related Documentation++- [Markets (Store SDK)](/v5/developer/sdk/store/markets) — Listing, resolving, and reading markets from the Store SDK+- [Pricing](/v5/developer/core-concepts/pricing) — Price Lists, Price Rules, and the Pricing Context+- [Addresses](/v5/developer/core-concepts/addresses) — Countries, States, and Zones+- [Localization](/api-reference/store-api/localization) — Locale, currency, and country headers in API requests+- [Translations](/v5/developer/core-concepts/translations) — Resource and UI translationsdiff --git a/docs/v5/developer/core-concepts/media.mdx b/docs/v5/developer/core-concepts/media.mdxnew file mode 100644index 0000000000..8c669b5bd1--- /dev/null+++ b/docs/v5/developer/core-concepts/media.mdx@@ -0,0 +1,383 @@+---+title: Media+sidebarTitle: "Media"+description: Manage product media in Spree — images, hosted and external video, named variants, focal points, and how media is uploaded, resized, and served via the Store API.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/media"+---++import { Since } from '/snippets/since.mdx';++## Overview++Spree handles uploads, processing, and delivery for product media. Images are automatically converted to WebP format and preprocessed into multiple sizes for optimal performance.++## Product Media++A media record carries:++- **Position** for ordering within the gallery+- **Media type** — `image`, `video`, or `external_video` (defaults to `image`)+- **Alt text** for accessibility and SEO+- **Focal point** coordinates for smart cropping+- **Preprocessed named variants** for fast delivery+- **`variant_ids`** — which product variants the media represents. An empty array means it represents the product as a whole.++### Product-level Gallery <Since version="5.5" />++In Spree 5.5 the **product** is the default owner of media. Before 5.5, every image was pinned to a specific variant (usually the master), and sharing the same image across variants meant re-uploading the file. From 5.5 onward, an image lives on the product, and any subset of variants can reference it through `variant_ids` — without duplicating the underlying file.++#### Uploading a product-level image++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({ baseUrl, secretKey })++// `signed_id` comes from a direct upload; see the Active Storage docs for+// generating one client-side.+const media = await client.products.media.create('prod_86Rf07xd4z', {+ signed_id: signedBlobId,+ alt: 'Front view',+ position: 1,+})+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/admin/products/prod_86Rf07xd4z/media' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{+ "signed_id": "<signed-blob-id>",+ "alt": "Front view",+ "position": 1+ }'+```++</CodeGroup>++#### Creating media from a remote URL++When the image already lives at a public URL, pass `url` instead of a `signed_id` — Spree fetches the remote file and stores it as product media, so you skip the direct-upload step entirely.++<CodeGroup>++```typescript Admin SDK+await client.products.media.create('prod_86Rf07xd4z', {+ url: 'https://cdn.example.com/images/tote-front.jpg',+ position: 1,+})+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/admin/products/prod_86Rf07xd4z/media' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{+ "url": "https://cdn.example.com/images/tote-front.jpg",+ "position": 1+ }'+```++</CodeGroup>++<Note>+The fetch runs in the background, so this request returns `202 Accepted` with no body — the media appears in the gallery once the download and processing finish. Re-fetch the product's media to know when it's ready.+</Note>++#### Sharing a single image across variants++Pass a `variant_ids` array on the same media endpoint to link/unlink variants. The server replaces the asset's link set on every call — empty array clears all links, omitting the field leaves them untouched.++<CodeGroup>++```typescript Admin SDK+await client.products.media.update('prod_86Rf07xd4z', 'media_k5nR8xLq', {+ variant_ids: ['variant_redM', 'variant_redL'],+})+```++```bash cURL+curl -X PATCH 'https://api.mystore.com/api/v3/admin/products/prod_86Rf07xd4z/media/media_k5nR8xLq' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{ "variant_ids": ["variant_redM", "variant_redL"] }'+```++</CodeGroup>++Variants belonging to a different product are silently dropped — the API rejects cross-product tampering at the model layer. Reordering happens once on the product gallery; every linked variant inherits the new order.++#### Storefront gallery resolution++The Store API's `media` field on a product returns its gallery — product-level media when present, falling back to legacy variant-pinned images during the transition. On a variant, `media` returns the assets linked to that variant via `variant_ids`, falling back to direct variant uploads.++This dual rendering means existing storefronts keep working during the upgrade; new uploads attach to the product, and you opt into a [one-shot migration](/v5/developer/upgrades/5.4-to-5.5) to re-home legacy variant-pinned data when convenient.++### Video <Since version="6.0" />++A product gallery can hold video as well as images. Spree supports both ways merchants usually have it:++| `media_type` | What it is | What it needs |+|---|---|---|+| `video` | A video file you upload, served from your own storage | An uploaded file (MP4, WebM, or QuickTime) |+| `external_video` | A YouTube or Vimeo link | The link, in `external_video_url` |++Spree reads the link once, when it is saved, and rejects anything it cannot embed — so a broken URL is caught at the point a merchant enters it rather than in the storefront. What it derives comes back on the media object:++| Field | Description |+|---|---|+| `video_provider` | `youtube` or `vimeo` |+| `video_embed_url` | Player URL, ready for an `iframe` |+| `video_url` | The uploaded file itself, for hosted video |+| `poster_url` | A still frame for the video |++Because the derived fields are on the response, a storefront embeds a video without parsing links itself.++#### Adding an external video++<CodeGroup>++```typescript Admin SDK+const video = await client.products.media.create('prod_86Rf07xd4z', {+ media_type: 'external_video',+ external_video_url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',+ alt: 'How it is made',+})++video.video_embed_url // https://www.youtube.com/embed/dQw4w9WgXcQ+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/admin/products/prod_86Rf07xd4z/media' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{+ "media_type": "external_video",+ "external_video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",+ "alt": "How it is made"+ }'+```++</CodeGroup>++#### Uploading a video file++A hosted video is uploaded the same way an image is, with `media_type` telling Spree what it is. Add `poster_signed_id` to give it a still frame:++```typescript Admin SDK+const video = await client.products.media.create('prod_86Rf07xd4z', {+ media_type: 'video',+ signed_id: signedVideoBlobId,+ poster_signed_id: signedPosterBlobId,+ alt: 'Product in use',+})+```++A poster can also be added or replaced later, on its own:++```typescript Admin SDK+await client.products.media.update('prod_86Rf07xd4z', 'media_k5nR8xLq', {+ poster_signed_id: signedPosterBlobId,+})+```++<Info>+Spree serves an uploaded video as you uploaded it — it does not transcode. Keep files web-friendly (H.264 MP4 or WebM) so they play everywhere, and prefer an external video for long footage so the provider handles streaming.+</Info>++#### Posters++A video has no image of its own, so its sized URLs (`small_url`, `large_url`, and the rest) resolve to its **poster** — the still shown before the video plays. A gallery that only knows how to draw an image still renders the right picture, and can play the video when the shopper asks for it.++Where the poster comes from, in order:++1. **The one the merchant uploaded** — `poster_signed_id` on write, editable in the dashboard's media editor.+2. **The provider's own still**, for a YouTube link.+3. **Nothing**, for a Vimeo link or an uploaded file with no poster — the tile falls back to a placeholder.++Spree does not extract a frame from an uploaded video, so give hosted video and Vimeo links a poster if you want them to show a still.++### Focal Point <Since version="6.0" />++`focal_point_x` and `focal_point_y` mark the part of an image that must stay in frame when a storefront crops it to a different shape. Both are fractions between 0 and 1, measured from the top left, so `{ x: 0.5, y: 0.5 }` is dead centre — which is also what a storefront should assume when they are null.++```typescript Admin SDK+await client.products.media.update('prod_86Rf07xd4z', 'media_k5nR8xLq', {+ focal_point_x: 0.25,+ focal_point_y: 0.4,+})+```++Spree stores the focal point and serves it; the cropping itself is the storefront's decision, since only it knows the shape it needs.++### Named Variant Sizes <Since version="5.3" />++When an image is uploaded, Spree automatically generates optimized versions in the background:++| Name | Dimensions | Use Case |+|------|------------|----------|+| `mini` | 128x128 | Thumbnails, cart items |+| `small` | 256x256 | Product listings, galleries |+| `medium` | 400x400 | Product cards, category pages |+| `large` | 720x720 | Product detail pages |+| `xlarge` | 2000x2000 | Zoom, high-resolution displays |++All variants are cropped to fill the exact dimensions and converted to WebP format.++## Store API++### Thumbnails (Always Available)++Every product response includes a `thumbnail_url` field — ready to use without any expands. Similarly, each variant includes a `thumbnail_url` and a `media_count` counter.++<CodeGroup>++```typescript Store SDK+// List products — thumbnail_url is always included+const { data: products } = await client.products.list({ limit: 12 })++products.forEach(product => {+ product.thumbnail_url // "https://cdn.../tote-front.webp" — no expand needed+})+```++```typescript Admin SDK+const { data: products } = await adminClient.products.list({ limit: 12 })+```++```bash cURL+# thumbnail_url is always in the response — no ?expand needed+curl 'https://api.mystore.com/api/v3/store/products?limit=12' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++<Warning>+Avoid using `?expand=media` on listing pages. This loads **all** media for every product in the response. Use `thumbnail_url` instead and only expand full media on product detail pages.+</Warning>++### Full Media (On Demand)++On the product detail page, [expand media and variants](/api-reference/store-api/relations) to get the full set of media with all named variant URLs:++<CodeGroup>++```typescript Store SDK+const product = await client.products.get('spree-tote', {+ expand: ['media', 'variants'],+})++// Product media gallery+product.media // [{ id, media_type, product_id, variant_ids, original_url, mini_url, ..., alt, position }, ...]++// Each variant has its own thumbnail and media_count+product.variants?.forEach(variant => {+ variant.thumbnail_url // "https://cdn.../tote-red.webp" — present in the response, null when the variant has no media+ variant.media_count // 3 — quick check without loading media+ variant.media // full media array (only with ?expand=media)+})+```++```typescript Admin SDK+const product = await adminClient.products.get('prod_86Rf07xd4z', {+ expand: ['media', 'variants'],+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products/spree-tote?expand=media,variants' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++**Response (media object):**++```json+{+ "id": "media_k5nR8xLq",+ "media_type": "image",+ "product_id": "prod_86Rf07xd4z",+ "variant_ids": ["variant_m3Rp9wXz"],+ "position": 1,+ "alt": "Front view",+ "focal_point_x": null,+ "focal_point_y": null,+ "external_video_url": null,+ "original_url": "https://cdn.example.com/images/original.jpg",+ "mini_url": "https://cdn.example.com/images/mini.webp",+ "small_url": "https://cdn.example.com/images/small.webp",+ "medium_url": "https://cdn.example.com/images/medium.webp",+ "large_url": "https://cdn.example.com/images/large.webp",+ "xlarge_url": "https://cdn.example.com/images/xlarge.webp"+}+```++### Media Fields Summary++| Field | Available on | Always Returned | Description |+|-------|-------------|:---:|-------------|+| `thumbnail_url` | Product | Yes | URL to the product's first media |+| `thumbnail_url` | Variant | Yes | URL to the variant's first media |+| `media_count` | Variant | Yes | Number of media items (counter cache) |+| `media` | Product, Variant | No | Full media array (requires `?expand=media`) |++### Media Object Fields++| Field | Type | Description |+|-------|------|-------------|+| `id` | string | Prefixed ID (`media_xxx`) |+| `media_type` | string | `image`, `video`, or `external_video` |+| `product_id` | string \| null | Owning product prefixed ID |+| `variant_ids` | string[] | Associated variant prefixed IDs (empty = product-level) |+| `position` | number | Sort order |+| `alt` | string \| null | Alt text |+| `focal_point_x` | number \| null | Horizontal focal point (0.0–1.0) |+| `focal_point_y` | number \| null | Vertical focal point (0.0–1.0) |+| `external_video_url` | string \| null | External video URL (YouTube/Vimeo) |+| `video_provider` | string \| null | `youtube` or `vimeo`, derived from the link <Since version="6.0" /> |+| `video_embed_url` | string \| null | Embeddable player URL, derived from the link <Since version="6.0" /> |+| `video_url` | string \| null | Uploaded video file URL <Since version="6.0" /> |+| `poster_url` | string \| null | Still frame for a video <Since version="6.0" /> |+| `original_url` | string \| null | Full-size image URL (inline disposition) |+| `mini_url` ... `xlarge_url` | string \| null | Named variant URLs |+| `download_url` | string \| null | Same blob as `original_url` but with `Content-Disposition: attachment`. Admin API only. <Since version="5.5" /> |++## Image Processing++Spree uses [libvips](https://www.libvips.org/) for image processing. Images are automatically:++- Converted to **WebP format** for optimal file size+- **Preprocessed on upload** into all named variant sizes+- **Cached** for subsequent requests++## Storage++Spree supports two storage service types:++| Service | Purpose | Examples |+|---------|---------|---------|+| Public storage | Product images, logos, taxon images | S3 public bucket, CDN |+| Private storage | CSV exports, digital downloads | S3 private bucket |++<Info>+For production deployments, use cloud storage (S3, GCS, Azure) instead of local disk storage. See [Asset Deployment](/v5/developer/deployment/assets) for configuration details.+</Info>++## Best Practices++- **Use `thumbnail_url`** on listing pages — avoid loading full media via expand+- **Always provide alt text** for accessibility and SEO+- **Use named variant sizes** (`mini`, `small`, `medium`, `large`, `xlarge`) for optimal performance+- **Use a CDN** in production for faster delivery+- **Give every video a poster** so a gallery has something to show before playback++## Related Documentation++- [Products](/v5/developer/core-concepts/products) — Product catalog and media+- [Products & Categories](/v5/developer/sdk/store/products) — Store SDK guide for fetching products, `thumbnail_url`, and expanded media+- [Admin SDK](/v5/developer/sdk/admin/resources) — Admin SDK resource methods, including the nested `products.media` create/update calls+- [Deployment — Assets](/v5/developer/deployment/assets) — Storage and CDN configurationdiff --git a/docs/v5/developer/core-concepts/metafields.mdx b/docs/v5/developer/core-concepts/metafields.mdxnew file mode 100644index 0000000000..92d90af43a--- /dev/null+++ b/docs/v5/developer/core-concepts/metafields.mdx@@ -0,0 +1,308 @@+---+title: Metafields+description: Add custom structured data to products, orders, and other resources with type-safe metafields+canonical: "https://spreecommerce.org/docs/developer/core-concepts/metafields"+---++import { Since } from '/snippets/since.mdx';++<Since version="5.2" />++## Overview++Metafields provide a flexible, type-safe system for adding custom structured attributes to Spree models. Unlike [metadata](/v5/developer/customization/metadata) which is simple JSON storage, metafields are schema-defined with strong typing, validation, and visibility controls.++Use metafields for:++- Product specifications (manufacturer, material, dimensions)+- Custom business logic fields+- Integration data from external systems+- Order-specific custom attributes++## Architecture++```mermaid+erDiagram+ MetafieldDefinition ||--o{ Metafield : "defines schema for"+ Product ||--o{ Metafield : "has many"+ Variant ||--o{ Metafield : "has many"+ Order ||--o{ Metafield : "has many"++ MetafieldDefinition {+ string namespace+ string key+ string name+ string metafield_type+ string resource_type+ string display_on+ boolean searchable+ boolean sortable+ }++ Metafield {+ string type+ text value+ string resource_type+ }+```++```mermaid+flowchart LR+ subgraph Definition+ A[MetafieldDefinition] --> B["namespace: properties"]+ A --> C["key: manufacturer"]+ A --> D["type: ShortText"]+ A --> E["resource_type: Product"]+ A --> F["display_on: both"]+ end++ subgraph Instance+ G[Metafield] --> H["value: Wilson"]+ G --> I["resource: Product #1"]+ end++ A -.->|"defines schema"| G+```++- **MetafieldDefinition** — the blueprint that defines the data type, target resource, and visibility+- **Metafield** — stores the actual value for a specific resource instance++## Data Types++| Type | Description | Example Values |+|------|-------------|----------------|+| Short Text | Brief text fields | SKU codes, brand names, tags |+| Long Text | Longer text content | Care instructions, notes |+| Rich Text | Formatted HTML content | Product descriptions with formatting |+| Number | Numeric values | Weight, quantity, ratings |+| Boolean | True/false flags | Is featured, requires signature |+| JSON | Structured data | Configuration, complex objects |++## Visibility Control++Metafields support two visibility levels via the `display_on` attribute:++| Visibility | Store API | Admin API | Use Case |+|------------|:---------:|:---------:|----------|+| `both` | Yes | Yes | Public product specifications |+| `back_end` | No | Yes | Internal notes, integration IDs |++## Search, sort & filter++Product metafield definitions can opt into SearchProvider participation:++| Flag | Effect | Allowed field types |+|------|--------|---------------------|+| `searchable` | Values are included in product text search | `short_text`, `long_text`, `number` |+| `sortable` | Listings can sort with `sort=cf_{namespace}_{key}` (prefix `-` for descending), e.g. `cf_custom_label` | `short_text`, `number` |++Both default to `false`. Set them on the definition (Admin UI, Admin API, or seeds). For an existing catalog with Meilisearch, run `rake spree:search:reindex` after toggling flags so index settings and product documents pick up new `cf_*` fields.++### Filtering++Any definition with either flag set also becomes filterable on product listings, using its `cf_*` key as a Ransack predicate. The Store and Admin APIs accept the same keys and the same `sort` values:++```+GET /api/v3/store/products?q[cf_custom_material_i_cont]=wool+GET /api/v3/admin/products?q[cf_custom_weight_gteq]=3.5+GET /api/v3/store/products?sort=-cf_custom_weight+```++| Field type | Predicates |+|------------|------------|+| `short_text`, `long_text` | `i_cont`, `cont`, `eq`, `not_eq`, `start`, `end`, `present`, `blank` |+| `number` | `eq`, `gt`, `gteq`, `lt`, `lteq`, `present`, `blank` |++Use `i_cont` for case-insensitive matching — plain `cont` is case-sensitive on PostgreSQL.++Predicates that don't match the definition's field type are ignored rather than rejected, as are keys matching no definition. Meilisearch supports the equality, range, and `present`/`blank` predicates; substring predicates (`i_cont`, `cont`, `start`, `end`) apply only to the database provider.++CSV exports honor the same predicates, so exporting a filtered product list matches what the admin sees.++In the admin dashboard, these fields appear in the products table's column selector, Sort dropdown, and filter panel — hidden by default, so admins opt in per column.++## Supported Resources++Metafields can be attached to most Spree resources including Products, Variants, Orders, Line Items, Taxons, Payments, Shipments, Gift Cards, Store Credits, and more.++<Info>+Custom resources can also support metafields. See the [Customization Quickstart](/v5/developer/customization/quickstart) for details.+</Info>++## Namespaces++Namespaces organize metafields into logical groups and prevent key conflicts:++| Namespace | Example Keys | Purpose |+|-----------|-------------|---------|+| `properties` | `manufacturer`, `material`, `fit` | Product specifications |+| `shopify` | `product_id`, `variant_id` | Integration data |+| `flags` | `featured`, `requires_approval` | Feature flags |+| `custom` | `gift_message`, `delivery_notes` | Business-specific fields |++<Info>+Namespace and key are automatically normalized to snake_case.+</Info>++## Store API++Metafields with `display_on` set to `both` are included in Store API responses when you [request the `custom_fields` expand](/api-reference/store-api/relations):++<Info>+ Metafields in API are called Custom Fields as we plan to rename Metafields to Custom Fields completely in Spree 6.0.+</Info>++<CodeGroup>++```typescript Store SDK+const product = await client.products.get('spree-tote', {+ expand: ['custom_fields'],+})++product.custom_fields?.forEach(field => {+ console.log(field.key) // "properties.manufacturer"+ console.log(field.label) // "Manufacturer"+ console.log(field.value) // "Wilson"+ console.log(field.field_type) // "short_text"+})+```++```typescript Admin SDK+const product = await adminClient.products.get('prod_86Rf07xd4z', {+ expand: ['custom_fields'],+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products/spree-tote?expand=custom_fields' \+ -H 'X-Spree-Api-Key: pk_xxx'+```++</CodeGroup>++**Response:**++```json+{+ "id": "prod_86Rf07xd4z",+ "name": "Spree T-Shirt",+ "custom_fields": [+ {+ "id": "cf_k5nR8xLq",+ "label": "Manufacturer",+ "key": "properties.manufacturer",+ "field_type": "short_text",+ "value": "Wilson"+ },+ {+ "id": "cf_m3Rp9wXz",+ "label": "Material",+ "key": "properties.material",+ "field_type": "short_text",+ "value": "100% Cotton"+ }+ ]+}+```++<Note>+The `display_on` attribute is intentionally excluded from Store API responses for security.+</Note>++## Admin Management++### Managing Definitions++Navigate to **Settings → Metafield Definitions** in the Admin Panel to create and manage metafield definitions. Select the resource type, enter namespace and key, choose the data type, and set visibility.++Definitions are also [managed via the Admin API](/api-reference/admin-api/endpoints). `storefront_visible: true` is equivalent to `display_on: both` — it exposes the field to the Store API:++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++const definition = await client.customFieldDefinitions.create({+ resource_type: 'Spree::Product',+ namespace: 'properties',+ key: 'manufacturer',+ label: 'Manufacturer',+ field_type: 'short_text',+ storefront_visible: true,+})++await client.customFieldDefinitions.update(definition.id, { storefront_visible: false })+await client.customFieldDefinitions.delete(definition.id)+```++```bash CLI+spree api post /custom_field_definitions -d '{+ "resource_type": "Spree::Product",+ "namespace": "properties",+ "key": "manufacturer",+ "label": "Manufacturer",+ "field_type": "short_text",+ "storefront_visible": true+}'+```++</CodeGroup>++### Managing Values++When editing a resource (e.g., a product), metafields appear in a dedicated section. The admin panel automatically builds forms for all defined metafields.++To set a value programmatically, use the resource's nested `customFields` accessor (parent ID first):++<CodeGroup>++```typescript Admin SDK+await client.products.customFields.create('prod_xxx', {+ custom_field_definition_id: 'cfdef_xxx',+ value: 'Wilson',+})+```++```bash CLI+spree api post /products/prod_xxx/custom_fields -d '{+ "custom_field_definition_id": "cfdef_xxx",+ "value": "Wilson"+}'+```++</CodeGroup>++## Metafields vs Metadata++Spree has two permanent, complementary systems for custom data — **metadata for machines, metafields for humans**. They serve different purposes and are not interchangeable. Neither is going away.++| Feature | Metafields | [Metadata](/v5/developer/customization/metadata) |+|---------|-----------|----------|+| **Purpose** | Merchant-defined structured attributes | Developer escape hatch — integration IDs, sync state |+| **Schema** | Defined via MetafieldDefinitions | Schemaless JSON — no definition required |+| **Validation** | Type-specific (text, number, boolean, etc.) | None — accepts any JSON-serializable data |+| **Visibility** | Configurable (admin-only or public) | Write-only in Store API, readable in Admin API |+| **Admin UI** | Dedicated management forms | JSON preview |+| **Data Types** | 6 specific types | Any JSON value |+| **Organization** | Namespaced (`namespace.key`) | Flat key-value structure |+| **Queryable** | Via SQL joins, Ransack scopes, search providers | Via JSONB operators (PostgreSQL) |++**Use Metafields** when you need type validation, visibility control, admin UI forms, or organized namespacing.++**Use [Metadata](/v5/developer/customization/metadata)** for external system IDs, tracking attribution, syncing with integrations, or simple write-and-forget data that only backend systems need to read.++<Warning>+Product Properties are deprecated and will be removed in Spree 6.0. For new projects, always use Metafields. For existing projects, plan to migrate using the [migration guide](/v5/developer/upgrades/5.1-to-5.2#migrate-to-metafields-or-keep-using-product-properties).+</Warning>++## Related Documentation++- [Metadata](/v5/developer/customization/metadata) — Simple key-value metadata+- [Products](/v5/developer/core-concepts/products) — Product catalog+- [Events](/v5/developer/core-concepts/events) — Subscribe to metafield events+- [Admin SDK](/v5/developer/sdk/admin/resources) — Manage definitions and values from TypeScriptdiff --git a/docs/v5/developer/core-concepts/orders.mdx b/docs/v5/developer/core-concepts/orders.mdxnew file mode 100644index 0000000000..1620e06eca--- /dev/null+++ b/docs/v5/developer/core-concepts/orders.mdx@@ -0,0 +1,420 @@+---+title: Orders+description: How Spree models orders — the cart-to-completion lifecycle, checkout state machine, line items, payments, shipments, and order totals.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/orders"+---++## Overview++An order is the central model connecting a customer to their purchase. It collects line items, addresses, shipments, payments, and adjustments into a single transaction that flows through a checkout state machine from cart to completion.++```mermaid+erDiagram+ Order ||--o{ LineItem : "has many"+ Order ||--o{ Shipment : "has many"+ Order ||--o{ Payment : "has many"+ Order ||--o{ Adjustment : "has many"+ Order }o--|| Address : "ship_address"+ Order }o--|| Address : "bill_address"+ Order }o--|| User : "belongs to"+ Order }o--|| Store : "belongs to"+ LineItem }o--|| Variant : "belongs to"+ Shipment }o--|| StockLocation : "ships from"+ Payment }o--|| PaymentMethod : "belongs to"++ Order {+ string number+ string state+ string email+ string currency+ decimal total+ string payment_state+ string shipment_state+ }++ LineItem {+ integer quantity+ decimal price+ }++ Shipment {+ string number+ string state+ string tracking+ }++ Payment {+ decimal amount+ string state+ }+```++**Key relationships:**+- **Line Items** link orders to [Variants](/v5/developer/core-concepts/products#variants) (what was purchased)+- **[Shipments](/v5/developer/core-concepts/shipments)** handle fulfillment from stock locations+- **[Payments](/v5/developer/core-concepts/payments)** track payment attempts and their states+- **[Adjustments](/v5/developer/core-concepts/adjustments)** apply taxes, promotions, and shipping costs+- **[Addresses](/v5/developer/core-concepts/addresses)** store billing and shipping information++## Order Attributes++The API returns these key fields on every order:++| Attribute | Description |+|-----------|-------------|+| `number` | Unique order number (e.g., `R123456789`), shown to customers |+| `email` | Customer's email address |+| `currency` | Order currency (e.g., `USD`) |+| `total_quantity` | Total number of items |+| `item_total` / `display_item_total` | Sum of line item prices |+| `delivery_total` / `display_delivery_total` | Delivery cost |+| `tax_total` / `display_tax_total` | Total tax |+| `discount_total` / `display_discount_total` | Total discount from promotions |+| `adjustment_total` / `display_adjustment_total` | Sum of all adjustments (tax + delivery + promos) |+| `total` / `display_total` | Final order total |+| `payment_status` | Payment status (`balance_due`, `paid`, `credit_owed`, `failed`, `void`) |+| `fulfillment_status` | Fulfillment status (`pending`, `ready`, `partial`, `shipped`, `backorder`) |+| `completed_at` | Timestamp when the order was placed |++The [`display_*` fields return formatted strings with currency symbols](/api-reference/store-api/monetary-amounts) (e.g., `"$15.99"`).++## Cart++A cart is simply an order in the `cart` state. Guest carts are [identified by a cart token; authenticated users' carts are linked to their account](/api-reference/store-api/authentication).++<CodeGroup>++```typescript Store SDK+// Create a cart+const cart = await client.carts.create()+// cart.token => "abc123" (save this for guest checkout)++// Get existing cart+const cart = await client.carts.get(cartId, { spreeToken: 'xxx' })++// Add an item+const updatedOrder = await client.carts.items.create(cart.id, {+ variant_id: 'var_xxx',+ quantity: 2,+})++// Update quantity+await client.carts.items.update(cart.id, 'li_xxx', {+ quantity: 3,+})++// Remove an item+await client.carts.items.delete(cart.id, 'li_xxx')+```++```bash cURL+# Create a cart+curl -X POST 'https://api.mystore.com/api/v3/store/carts' \+ -H 'X-Spree-API-Key: pk_xxx'++# Get existing cart+curl 'https://api.mystore.com/api/v3/store/carts/cart_xxx' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Token: abc123'++# Add an item+curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_xxx/items' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Token: abc123' \+ -H 'Content-Type: application/json' \+ -d '{ "variant_id": "var_xxx", "quantity": 2 }'++# Update quantity+curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx/items/li_xxx' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Token: abc123' \+ -H 'Content-Type: application/json' \+ -d '{ "quantity": 3 }'++# Remove an item+curl -X DELETE 'https://api.mystore.com/api/v3/store/carts/cart_xxx/items/li_xxx' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Token: abc123'+```++</CodeGroup>++Every item mutation returns the full updated order with recalculated totals.++## Checkout Flow++The checkout is a state machine that advances the order through a series of steps. Each step collects required information before allowing the order to proceed.++<Steps>+ <Step title="cart">+ Customer has items in their cart. This is the starting state.+ </Step>+ <Step title="address">+ Customer provides shipping and billing addresses.+ </Step>+ <Step title="delivery">+ Customer selects a shipping rate for each shipment.+ </Step>+ <Step title="payment">+ Customer provides payment. Skipped if the order is fully covered by store credit.+ </Step>+ <Step title="confirm">+ Customer reviews and confirms the order.+ </Step>+ <Step title="complete">+ Order is placed. `completed_at` is set and fulfillment begins.+ </Step>+</Steps>++If the order doesn't meet the requirements for the next state (e.g., missing address), the API returns an error.++<CodeGroup>++```typescript Store SDK+// Set addresses+await client.carts.update(cartId, {+ email: '[email protected]',+ shipping_address: {+ first_name: 'John', last_name: 'Doe',+ address1: '123 Main St', city: 'Los Angeles',+ country_iso: 'US', state_abbr: 'CA', postal_code: '90001',+ phone: '555-0100',+ },+})++// Get fulfillments and select a delivery rate+// (the Store API/SDK exposes shipments as `fulfillments`)+const cart = await client.carts.get(cartId)+await client.carts.fulfillments.update(cartId, cart.fulfillments[0].id, {+ selected_delivery_rate_id: 'rate_xxx',+})++// Create a payment session (e.g., Stripe)+const session = await client.carts.paymentSessions.create(cartId, {+ payment_method_id: 'pm_xxx',+})+// session.external_data.client_secret => use with Stripe.js++// Complete the payment session after provider confirmation+await client.carts.paymentSessions.complete(cartId, session.id)++// Complete the order+await client.carts.complete(cartId)+```++```bash cURL+# Set addresses+curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Token: abc123' \+ -H 'Content-Type: application/json' \+ -d '{+ "email": "[email protected]",+ "shipping_address": {+ "first_name": "John", "last_name": "Doe",+ "address1": "123 Main St", "city": "Los Angeles",+ "country_iso": "US", "state_abbr": "CA", "postal_code": "90001",+ "phone": "555-0100"+ }+ }'++# Select a delivery rate+curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx/fulfillments/ful_xxx' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Token: abc123' \+ -H 'Content-Type: application/json' \+ -d '{ "selected_delivery_rate_id": "rate_xxx" }'++# Complete the order+curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_xxx/complete' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Token: abc123'+```++</CodeGroup>++## Coupon Codes++Apply or remove promotional coupon codes during checkout:++<CodeGroup>++```typescript Store SDK+// Apply a discount code+await client.carts.discountCodes.apply(cartId, 'SAVE20')++// Remove a discount code+await client.carts.discountCodes.remove(cartId, 'SAVE20')+```++```bash cURL+# Apply a discount code+curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_xxx/discount_codes' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Token: abc123' \+ -H 'Content-Type: application/json' \+ -d '{ "code": "SAVE20" }'++# Remove a discount code+curl -X DELETE 'https://api.mystore.com/api/v3/store/carts/cart_xxx/discount_codes/SAVE20' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Token: abc123'+```++</CodeGroup>++## Order History++Authenticated customers can view their past orders:++<CodeGroup>++```typescript Store SDK+// List past orders+const { data: orders } = await client.customer.orders.list()++// Get a specific order with details+const order = await client.orders.get('or_xxx', {+ expand: ['items', 'fulfillments', 'payments'],+})+```++```typescript Admin SDK+const order = await adminClient.orders.get('or_xxx')+```++```bash cURL+# List past orders+curl 'https://api.mystore.com/api/v3/store/customer/orders' \+ -H 'Authorization: Bearer <jwt_token>'++# Get a specific order+curl 'https://api.mystore.com/api/v3/store/orders/or_xxx?expand=items,fulfillments,payments' \+ -H 'Authorization: Bearer <jwt_token>'+```++</CodeGroup>++## Managing Orders++Everything above is the **Store API** — the customer's own cart and orders. Back-office order management (listing every order, creating phone/manual orders, capturing payments, cancelling) uses the [Admin API](/api-reference/admin-api/introduction).++### Listing and creating orders++List orders with [Ransack filters and pagination](/api-reference/admin-api/querying) (`state_eq`, `limit`, sorting). A draft order is created in one call; pass line items as `items` (each `{ variant_id, quantity }`):++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++// List orders (Ransack filters)+const { data: orders } = await client.orders.list({ state_eq: 'complete', limit: 25 })++// Create a draft order on a customer's behalf+const order = await client.orders.create({+ email: '[email protected]',+ items: [{ variant_id: 'variant_xxx', quantity: 2 }],+ currency: 'USD',+})+```++```bash CLI+spree api get /orders -q state_eq=complete --limit 25+spree api post /orders -d '{+ "email": "[email protected]",+ "items": [{ "variant_id": "variant_xxx", "quantity": 2 }]+}'+```++</CodeGroup>++### Order state actions++Orders move through their [state machine](#checkout-flow) via dedicated actions rather than raw `state` writes:++<CodeGroup>++```typescript Admin SDK+await client.orders.complete('or_xxx') // finalize a draft+await client.orders.cancel('or_xxx', { reason: 'customer' })+await client.orders.approve('or_xxx')+await client.orders.resume('or_xxx')+await client.orders.resendConfirmation('or_xxx')+```++```bash CLI+spree api patch /orders/or_xxx/complete+spree api patch /orders/or_xxx/cancel -d '{"reason": "customer"}'+spree api patch /orders/or_xxx/approve+```++</CodeGroup>++### Payments and refunds++Capture or void an authorized payment, and issue refunds, through the nested order resources:++<CodeGroup>++```typescript Admin SDK+await client.orders.payments.capture('or_xxx', 'pay_xxx')+await client.orders.payments.void('or_xxx', 'pay_xxx')+await client.orders.refunds.create('or_xxx', { payment_id: 'pay_xxx', amount: '19.99' })+```++```bash CLI+spree api patch /orders/or_xxx/payments/pay_xxx/capture+spree api post /orders/or_xxx/refunds -d '{"payment_id": "pay_xxx", "amount": "19.99"}'+```++</CodeGroup>++## Line Items++Line items represent individual products in an order. Each line item links to a [Variant](/v5/developer/core-concepts/products#variants) and tracks the quantity and price at the time of purchase.++When a variant is added to an order, the price is locked on the line item. If the variant's price changes later, existing orders are unaffected.++## Adjustments++[Adjustments](/v5/developer/core-concepts/adjustments) modify an order's total — promotions decrease it, taxes and shipping increase it. Adjustments can be applied at the order level, the line item level, or the shipment level.++## Payment States++| State | Description |+|-------|-------------|+| `balance_due` | Payment total is less than the order total |+| `paid` | Payment total equals the order total |+| `credit_owed` | Payment total exceeds the order total (refund pending) |+| `failed` | Most recent payment attempt failed |+| `void` | Order was canceled and payments voided |++## Fulfillment Statuses++The order's `fulfillment_status` field summarizes the state of all fulfillments (the Store API/SDK exposes shipments as `fulfillments`).++| Status | Description |+|--------|-------------|+| `pending` | All fulfillments are pending |+| `ready` | All fulfillments are ready to ship |+| `partial` | At least one fulfillment is shipped, others are not |+| `shipped` | All fulfillments have been shipped |+| `backorder` | Some inventory is on backorder |++For more details, see [Shipments](/v5/developer/core-concepts/shipments) and [Payments](/v5/developer/core-concepts/payments).++## Related Documentation++- [Cart, Checkout & Orders](/v5/developer/sdk/store/cart-checkout) — Store SDK guide for carts, checkout, coupon codes, and order history+- [Payments](/v5/developer/core-concepts/payments) — Payment processing and payment sessions+- [Shipments](/v5/developer/core-concepts/shipments) — Fulfillment and shipping rates+- [Addresses](/v5/developer/core-concepts/addresses) — Billing and shipping addresses+- [Promotions](/v5/developer/core-concepts/promotions) — Discounts and coupon codes+- [Checkout Customization](/v5/developer/customization/checkout) — Customizing the checkout flow+- [Events](/v5/developer/core-concepts/events) — Subscribe to order events (e.g., `order.completed`)diff --git a/docs/v5/developer/core-concepts/payments.mdx b/docs/v5/developer/core-concepts/payments.mdxnew file mode 100644index 0000000000..e6000b6025--- /dev/null+++ b/docs/v5/developer/core-concepts/payments.mdx@@ -0,0 +1,718 @@+---+title: Payments+canonical: "https://spreecommerce.org/docs/developer/core-concepts/payments"+---++## Overview++Spree has a highly flexible payments model which allows multiple payment methods to be available during the checkout. The logic for processing payments is decoupled from orders, making it easy to define custom payment methods with their own processing logic.++Payment methods typically represent a payment gateway. Gateways will process card payments, online bank transfers, buy-now-pay-later, wallet payments, and other types of payments. Spree also comes with a Check option for offline processing.++The `Payment` model in Spree tracks payments against [Orders](orders). Payments relate to a `source` which indicates how the payment was made, and a `PaymentMethod`, indicating the processor used for this payment.++When a payment is created, it is given a unique, 8-character identifier. This is used when sending the payment details to the payment processor. Without this identifier, some payment gateways mistakenly reported duplicate payments.++### Payment Architecture Diagram++```mermaid+erDiagram+ Payment {+ string number+ decimal amount+ string state+ string response_code+ string avs_response+ string source_type+ string source_id+ }++ PaymentMethod {+ string name+ string type+ string description+ boolean active+ string display_on+ integer position+ }++ PaymentSession {+ string status+ decimal amount+ string currency+ string external_id+ json external_data+ datetime expires_at+ }++ PaymentSetupSession {+ string status+ string external_id+ string external_client_secret+ json external_data+ }++ PaymentSource {+ string type+ string gateway_payment_profile_id+ }++ CreditCard {+ string last_digits+ string cc_type+ integer month+ integer year+ string name+ }++ GatewayCustomer {+ string profile_id+ }++ StoreCredit {+ decimal amount+ decimal amount_used+ decimal amount_authorized+ string currency+ }++ Refund {+ decimal amount+ integer refund_reason_id+ }++ Order ||--o{ Payment : "has many"+ Order ||--o{ PaymentSession : "has many"+ Payment }o--|| PaymentMethod : "belongs to"+ Payment }o--o| CreditCard : "source"+ Payment }o--o| PaymentSource : "source"+ Payment }o--o| StoreCredit : "source"+ Payment ||--o| PaymentSession : "linked via response_code"+ Payment ||--o{ Refund : "has many"+ PaymentMethod ||--o{ PaymentSession : "has many"+ PaymentMethod ||--o{ PaymentSetupSession : "has many"+ PaymentMethod ||--o{ GatewayCustomer : "has many"+ PaymentMethod }o--|| Store : "belongs to"+ PaymentSetupSession }o--o| PaymentSource : "creates"+ PaymentSetupSession }o--|| Customer : "belongs to"+ GatewayCustomer }o--|| Customer : "belongs to"+ CreditCard }o--|| Customer : "belongs to"+ StoreCredit }o--|| Customer : "belongs to"+ Refund }o--|| Payment : "belongs to"+ Refund }o--|| Reimbursement : "belongs to"+```++**Key relationships:**+- **Payment** tracks each payment attempt against an [Order](/v5/developer/core-concepts/orders)+- **Payment Method** defines how payments are processed (Stripe, Adyen, PayPal, Check, etc.)+- **Payment Session** manages the gateway-side payment lifecycle (e.g., Stripe PaymentIntent, Adyen Session)+- **Payment Setup Session** manages saving payment methods for future use without an immediate charge (e.g., Stripe SetupIntent)+- **Source** is polymorphic - can be a Credit Card, Payment Source (for alternative methods like Klarna, iDEAL), or Store Credit+- **Gateway Customer** stores the provider-specific customer profile (e.g., Stripe Customer ID)+- **Log Entries** record gateway responses for debugging+- **Refunds** track money returned to customers++## Payment Methods++Payment methods represent the different options a customer has for making a payment. Most sites will accept credit card payments through a payment gateway, but there are other options. Spree also comes with built-in support for a Check payment, which can be used to represent any offline payment. Gateway providers such as Stripe, Adyen, and PayPal provide a wide range of payment methods, including credit cards, bank transfers, buy-now-pay-later, and digital wallets (Apple Pay, Google Pay, etc.).++A `PaymentMethod` can have the following attributes:++| Attribute | Description | Example |+|--------------|-----------------------------------------------------------------------------------------------|------------------------|+| `type` | The payment method type | `Check` |+| `name` | The visible name for this payment method | `Check` |+| `description`| The description for this payment method | `Pay by check.` |+| `active` | Whether or not this payment method is active. Set it `false` to hide it in the Store API. | `true` |+| `display_on` | Determines where the payment method can be visible. Values can be `front_end` (Store API), `back_end` (admin panel only), or `both` (both). | `both` |+| `position` | The position of the payment method in lists. Lower numbers appear first. | `1` |++<Info>+Each payment method is associated to a Store, so you can decide which Payment Method will appear on which Store. This allows you to create different experiences for your customers in different countries.+</Info>++### Session-based vs Legacy Payment Methods++Payment methods indicate whether they use the modern session-based flow via the `session_required?` method:++| Method | Description | Default |+|--------|-------------|---------|+| `session_required?` | Returns `true` if this payment method requires a Payment Session for processing. | `false` |+| `setup_session_supported?` | Returns `true` if this payment method supports saving payment methods for future use (Payment Setup Sessions). | `false` |+| `payment_session_class` | Returns the STI subclass of `Spree::PaymentSession` for this gateway (e.g., `Spree::PaymentSessions::Stripe`). | `nil` |+| `payment_setup_session_class` | Returns the STI subclass of `Spree::PaymentSetupSession` for this gateway. | `nil` |++Modern gateways like Stripe and Adyen set `session_required?` to `true`. The Store API serializer includes this as the `session_required` field so your frontend knows which flow to use.++### Non-Session Payment Methods (Manual/Offline)++Payment methods where `session_required?` returns `false` don't need a payment session. These are typically offline or manual payment methods such as:++- **Check** — built-in (`Spree::PaymentMethod::Check`)+- **Cash on Delivery** — customer pays upon delivery+- **Bank Transfer / Wire** — customer transfers money to a bank account+- **Purchase Order** — common in B2B, customer provides a PO number++For these methods, the Store API allows creating a payment directly without going through the payment session flow:++```typescript+const options = { spreeToken: cart.token }++// Create a payment for a non-session payment method+const payment = await client.carts.payments.create(cart.id, {+ payment_method_id: 'pm_xyz789',+ amount: '99.99', // Optional, defaults to order total minus store credits+ metadata: { // Optional, write-only metadata (e.g. PO number)+ purchase_order_number: 'PO-12345',+ },+}, options)+```++The payment is created in `checkout` state. When the order transitions to `complete`, Spree calls `process_payments!` which runs the payment method's `authorize` (or `purchase` if auto-capture is enabled). For manual payment methods like Check, this is a no-op that succeeds immediately — the payment moves to `pending` (or `completed` with auto-capture), allowing the order to complete.++The merchant can later capture or void the payment from the Admin Panel once the actual payment is received (e.g., check arrives, bank transfer clears, cash is collected on delivery).++## Payment Flow++Spree supports two payment flows depending on the payment method type:++### Session-Based Flow (Stripe, Adyen, PayPal, etc.)++Modern payment gateways use a three-phase approach: first a **Payment Session** is created with the gateway, then the customer completes payment on the frontend, and finally the **order is completed** via an explicit API call. Payment processing and order completion are intentionally separated — this prevents race conditions and ensures reliable checkout regardless of payment method type (cards, wallets, offsite redirects).++```mermaid+sequenceDiagram+ participant Frontend+ participant Spree API+ participant Payment Provider++ rect rgb(240, 245, 255)+ note right of Frontend: Phase 1: Payment Session+ Frontend->>Spree API: Create Payment Session+ Spree API->>Payment Provider: Create session (PaymentIntent/Session)+ Payment Provider-->>Spree API: Session ID + client_secret+ Spree API-->>Frontend: PaymentSession (pending)+ end++ rect rgb(240, 255, 240)+ note right of Frontend: Phase 2: Customer Pays+ Frontend->>Payment Provider: Collect payment (using client_secret)+ Note over Frontend,Payment Provider: 3DS / offsite redirect handled here+ Payment Provider-->>Frontend: Payment result+ end++ rect rgb(255, 248, 240)+ note right of Frontend: Phase 3: Complete Payment Session+ Frontend->>Spree API: Complete Payment Session+ Spree API->>Payment Provider: Verify payment status+ Spree API->>Spree API: Create Payment record+ Spree API-->>Frontend: PaymentSession (completed)+ end++ rect rgb(255, 240, 245)+ note right of Frontend: Phase 4: Complete Order+ Frontend->>Spree API: POST /carts/:id/complete+ Spree API->>Spree API: Validate & finalize order+ Spree API-->>Frontend: Completed order+ end+```++<Steps>+ <Step title="Create Payment Session">+ The frontend calls the API to create a Payment Session for a specific payment method and order. Spree calls the gateway to create a provider-side session (e.g., Stripe PaymentIntent, Adyen Session) and returns the session data including a `client_secret` for the frontend SDK.++ <Info>+ The payment session should be created (or recreated) **after** the shipping method is selected, so the amount includes shipping costs. If the order total changes (e.g., customer selects a different shipping rate or applies a coupon), create a new payment session with the updated amount.+ </Info>+ </Step>+ <Step title="Customer pays on the frontend">+ The frontend uses the gateway's JavaScript SDK (e.g., Stripe.js, Adyen Drop-in) with the `client_secret` to securely collect payment details. Card data never touches your server — it goes directly to the payment provider, ensuring [PCI compliance](/v5/developer/security/pci_compliance). If the payment requires **3D Secure** authentication or redirects to an offsite gateway (CashApp, Klarna, etc.), the gateway SDK handles it automatically.+ </Step>+ <Step title="Complete Payment Session">+ After the customer completes payment, the frontend calls the Complete Payment Session endpoint. Spree verifies the payment status with the gateway, creates a `Payment` record, creates the appropriate payment source (Credit Card, wallet, etc.), and marks the session as completed.++ **This step does NOT complete the order** — it only handles payment processing. For wallet payments (Apple Pay, Google Pay), the gateway also patches the order's billing address with data from the wallet at this stage.+ </Step>+ <Step title="Complete Order">+ The frontend calls `POST /carts/:id/complete` to finalize the order. Spree validates the order is ready (addresses, fulfillments, payment), advances through any remaining checkout states, and marks the order as complete.++ This separation ensures the same flow works for all payment types — inline cards, offsite redirects, and wallet payments.+ </Step>+</Steps>++#### Offsite Payment Flow (CashApp, 3D Secure, Klarna, etc.)++For payment methods that redirect the customer away from your site, use an intermediate **confirm-payment** page:++```mermaid+sequenceDiagram+ participant Frontend+ participant Gateway+ participant Spree API++ Frontend->>Gateway: confirmPayment (redirects to gateway)+ Gateway-->>Frontend: Redirect back to /confirm-payment/:id?session=...+ Frontend->>Spree API: Complete Payment Session+ Spree API-->>Frontend: Session completed+ Frontend->>Spree API: POST /carts/:id/complete+ Spree API-->>Frontend: Order completed+ Frontend->>Frontend: Redirect to thank-you page+```++#### Webhook-Driven Completion (Browser Closed)++If the customer closes the browser after paying but before the frontend calls `complete`, Spree handles this via payment webhooks:++```mermaid+sequenceDiagram+ participant Payment Provider+ participant Spree API++ Payment Provider->>Spree API: POST /api/v3/webhooks/payments/:pm_id+ Spree API->>Spree API: Verify signature+ Spree API->>Spree API: Enqueue HandleWebhookJob+ Spree API-->>Payment Provider: 200 OK++ note over Spree API: Async processing+ Spree API->>Spree API: Create/update Payment+ Spree API->>Spree API: Complete order via Carts::Complete+```++Gateway extensions implement `parse_webhook_event` to normalize provider-specific payloads into a standard format. Spree core handles the rest — creating the payment record, completing the session, and finalizing the order.++### Direct Payment Flow (Check, Cash on Delivery, Bank Transfer, etc.)++Non-session payment methods use a simpler flow where a payment is created directly without involving an external payment provider:++```mermaid+sequenceDiagram+ participant Frontend+ participant Spree API++ Frontend->>Spree API: GET /carts/:id+ Spree API-->>Frontend: Cart (with embedded payment_methods, each carrying session_required)++ Frontend->>Spree API: POST /payments (payment_method_id)+ Spree API->>Spree API: Create Payment (checkout state)+ Spree API-->>Frontend: Payment created++ Frontend->>Spree API: POST /carts/:id/complete+ Spree API->>Spree API: process_payments! (authorize succeeds immediately)+ Spree API->>Spree API: Payment → pending/completed+ Spree API-->>Frontend: Order completed+```++<Steps>+ <Step title="List payment methods">+ The frontend reads the cart's embedded `payment_methods` (returned by `GET /carts/:id`) and checks the `session_required` flag on each method. Methods with `session_required: false` use this direct flow.+ </Step>+ <Step title="Create payment">+ The frontend calls `POST /payments` with the `payment_method_id`. Spree creates a `Payment` record in `checkout` state. No external provider interaction is needed.+ </Step>+ <Step title="Complete order">+ The frontend completes the order. Spree's `process_payments!` runs the payment method's `authorize` (or `purchase` with auto-capture). For manual methods like Check, these return an immediate success — no external service is called. The payment transitions to `pending` (without auto-capture) or `completed` (with auto-capture) and the order completes. The merchant can later capture `pending` payments from the Admin Panel once the physical payment is received.+ </Step>+</Steps>++### Payment Session++A `PaymentSession` (`Spree::PaymentSession`) represents a server-side session with the payment gateway. It is the entry point for every payment attempt and holds the provider-specific data needed by the frontend SDK.++#### Attributes++| Attribute | Description | Example Value |+|-----------|-------------|---------------|+| `status` | Current session state: `pending`, `processing`, `completed`, `failed`, `canceled`, `expired` | `completed` |+| `amount` | The payment amount | `99.99` |+| `currency` | ISO currency code | `USD` |+| `external_id` | The provider-side session ID (e.g., Stripe PaymentIntent ID) | `pi_3ABC123` |+| `external_data` | Provider-specific data including `client_secret` for frontend SDK | `{"client_secret": "pi_3ABC_secret_xyz"}` |+| `customer_external_id` | The provider's customer ID | `cus_ABC123` |+| `expires_at` | When the session expires | `2025-01-01T12:00:00Z` |++#### States++```mermaid+stateDiagram-v2+ [*] --> pending+ pending --> processing+ pending --> completed+ pending --> failed+ pending --> canceled+ pending --> expired+ processing --> completed+ processing --> failed+ processing --> canceled+ processing --> expired+```++#### API++**Create a Payment Session:**++```typescript+const options = { spreeToken: cart.token }++// Create a payment session for the selected payment method+const session = await client.carts.paymentSessions.create(cart.id, {+ payment_method_id: 'pm_xyz789',+ amount: '99.99', // Optional, defaults to order total+ external_data: {}, // Optional, provider-specific data+}, options)++// The session contains provider-specific data for the frontend SDK+console.log(session.external_id) // e.g. 'pi_3ABC123' (Stripe PaymentIntent ID)+console.log(session.external_data.client_secret) // Use with Stripe.js or Adyen Drop-in+```++**Response shape (`StorePaymentSession`):**++```json+{+ "id": "ps_abc123",+ "status": "pending",+ "amount": "99.99",+ "currency": "USD",+ "external_id": "pi_3ABC123",+ "external_data": {+ "client_secret": "pi_3ABC123_secret_xyz"+ },+ "customer_external_id": "cus_ABC123",+ "expires_at": "2025-01-01T12:00:00Z",+ "payment_method_id": "pm_xyz789",+ "order_id": "or_ABC123",+ "payment": null+}+```++**Update a Payment Session** (e.g., after order total changes):++```typescript+const updated = await client.carts.paymentSessions.update(+ cart.id, session.id,+ { amount: '149.99' },+ options+)+```++**Complete a Payment Session** (after customer confirms payment on the frontend):++```typescript+const completed = await client.carts.paymentSessions.complete(+ cart.id, session.id,+ { session_result: '...', external_data: {} },+ options+)+console.log(completed.status) // 'completed'+```++<Warning>+Completing a payment session does **not** complete the order. You must call `POST /carts/:id/complete` separately after the session is completed. This separation prevents race conditions between the frontend and payment webhooks.+</Warning>++**Complete the Order** (after the payment session is completed):++```typescript+const order = await client.carts.complete(cart.id, options)+```++### Payment Webhooks++Spree provides a generic webhook endpoint at `POST /api/v3/webhooks/payments/:payment_method_id` that payment gateway extensions can use. When a payment provider sends a webhook (e.g., Stripe `payment_intent.succeeded`), Spree:++1. Verifies the webhook signature synchronously (returns `401` if invalid)+2. Enqueues a background job to process the event+3. Returns `200 OK` immediately++The background job creates/updates the Payment record, marks the session as completed, and completes the order if needed.++#### Gateway Interface++Gateway extensions implement `parse_webhook_event` to normalize provider-specific payloads:++```ruby+class MyGateway < Spree::Gateway+ def parse_webhook_event(raw_body, headers)+ # Verify signature — raise WebhookSignatureError if invalid+ event = verify_signature(raw_body, headers)++ case event.type+ when 'payment.captured'+ session = Spree::PaymentSession.find_by(external_id: event.payment_id)+ { action: :captured, payment_session: session }+ when 'payment.failed'+ session = Spree::PaymentSession.find_by(external_id: event.payment_id)+ { action: :failed, payment_session: session }+ else+ nil # unsupported event+ end+ end+end+```++Supported actions: `:captured`, `:authorized`, `:failed`, `:canceled`.++### Payment++Once a Payment Session is completed, Spree creates a `Payment` record (`Spree::Payment`) to track the result. The Payment is linked to the session via `response_code` matching the session's `external_id`.++#### Attributes++| Attribute | Description | Example Value |+|-------------------|-----------------------------------------------------------------------------|---------------------|+| `number` | A unique identifier for the payment. | `PAB12CD34` |+| `source_type` | The type of source used for the payment. | `Spree::CreditCard` |+| `source_id` | The ID of the source used for the payment. | `1` |+| `amount` | The amount of the payment. | `99.99` |+| `payment_method_id`| The ID of the payment method used. | `2` |+| `state` | The current state of the payment (e.g., processing, completed, failed). | `completed` |+| `response_code` | The gateway transaction ID. Links to the Payment Session's `external_id`. | `pi_3ABC123` |+| `avs_response` | The address verification system response code. | `D` |++#### Payment States++After a Payment Session completes, the resulting Payment transitions through these states:++```mermaid+stateDiagram-v2+ [*] --> checkout+ checkout --> processing : process!+ processing --> completed : purchase! succeeds+ processing --> pending : authorize! succeeds+ processing --> failed : payment declined+ pending --> completed : capture!+ pending --> void : void!+ completed --> void : void!+ checkout --> void : void!+```++| State | Description |+|-------|-------------|+| `checkout` | Initial state. The payment has been created but not yet processed. |+| `processing` | The payment is being processed (temporary - prevents double submission). |+| `pending` | The payment has been authorized but not yet captured. Awaiting manual or scheduled capture. |+| `failed` | The payment was rejected (e.g., card declined, insufficient funds). |+| `void` | The payment has been voided and should not be counted against the order. |+| `completed` | The payment has been captured. Only payments in this state count against the order total. |++With **auto-capture** enabled (default for most gateways), the Payment goes directly from `checkout` → `processing` → `completed`. With **manual capture**, it stops at `pending` until an admin captures it.++#### Order Payment States++Each payment update also recalculates the order's `payment_state`:++| Payment State | Description |+|---------------|-------------|+| `balance_due` | Payment is required for this order |+| `failed` | The last payment for the order failed |+| `credit_owed` | This order has been paid for in excess of its total |+| `paid` | This order has been paid for in full |++<Warning>+You may want to keep tabs on the number of orders with a `payment_state` of `failed`. A sudden increase could indicate a problem with your payment gateway and most likely a serious problem affecting customer satisfaction. Check your payment gateway's dashboard for the most recent transactions if this is happening.+</Warning>++## Payment Sources++Payment sources represent the actual instrument used for a payment. They are created automatically when a Payment Session completes.++### Credit Cards (`Spree::CreditCard`)++Stores non-sensitive credit card information. With modern gateways, the actual card data is tokenized by the provider - Spree only stores reference IDs and display information.++| Attribute | Description | Example Value |+|---------------------|-----------------------------------------------------------------------------------------------|------------------------|+| `month` | The month the credit card expires. | `6` |+| `year` | The year the credit card expires. | `2026` |+| `cc_type` | The type of credit card (e.g., visa, mastercard). | `visa` |+| `last_digits` | The last four digits of the credit card number. | `1234` |+| `name` | The name of the credit card holder. | `John Doe` |+| `gateway_payment_profile_id` | The payment token from the gateway (e.g., Stripe `pm_xxx`, Adyen `storedPaymentMethodId`). | `pm_1ABC123` |++<Note>+Spree never stores full credit card numbers. With modern gateways, card data is collected entirely by the gateway's frontend SDK (e.g., Stripe.js, Adyen Drop-in) and never touches your server. Spree only stores the tokenized reference (`gateway_payment_profile_id`) returned by the provider.+</Note>++### Payment Sources++A generic payment source model for non-card payment methods such as digital wallets, bank transfers, and buy-now-pay-later services. Gateway integrations create subtypes for each payment method type (e.g., Klarna, Afterpay, iDEAL, Apple Pay, Google Pay, PayPal).++### Gateway Customers (`Spree::GatewayCustomer`)++Maps a Spree customer to their provider-specific customer profile. This enables features like saved payment methods, recurring billing, and customer-level fraud detection.++| Attribute | Description | Example Value |+|-----------|-------------|---------------|+| `profile_id` | The provider's customer ID (encrypted at rest) | `cus_ABC123` |+| `payment_method_id` | The gateway this customer belongs to | `1` |+| `user_id` | The Spree user | `42` |++Each customer has at most one `GatewayCustomer` record per payment method. The `profile_id` is encrypted using Active Record Encryption when available.++## Payment Setup Sessions++Payment Setup Sessions (`Spree::PaymentSetupSession`) allow customers to save payment methods for future use **without making an immediate payment**. This maps to concepts like Stripe's SetupIntent - a secure way to collect and tokenize payment details for later charges.++### Use Cases++- Saving a credit card to the customer's account for faster future checkouts+- Authorizing a payment method for subscription billing+- Adding a payment method during account onboarding (before any purchase)++### How Payment Setup Sessions Work++```mermaid+sequenceDiagram+ participant Frontend+ participant Spree API+ participant Payment Provider++ Frontend->>Spree API: Create Payment Setup Session+ Spree API->>Payment Provider: Create setup session (SetupIntent)+ Payment Provider-->>Spree API: Session ID + client_secret+ Spree API-->>Frontend: PaymentSetupSession (pending)++ Frontend->>Payment Provider: Collect card details (using client_secret)+ Note over Frontend,Payment Provider: 3DS verification if needed++ Frontend->>Spree API: Complete Payment Setup Session+ Spree API->>Payment Provider: Verify setup result+ Spree API->>Spree API: Create PaymentSource (saved card)+ Spree API-->>Frontend: Completed PaymentSetupSession+```++### Payment Setup Session Attributes++| Attribute | Description | Example Value |+|-----------|-------------|---------------|+| `status` | Current session state: `pending`, `processing`, `completed`, `failed`, `canceled`, `expired` | `completed` |+| `external_id` | The provider-side session ID (e.g., Stripe SetupIntent ID) | `seti_ABC123` |+| `external_client_secret` | Client secret for the frontend SDK | `seti_ABC123_secret_xyz` |+| `external_data` | Provider-specific data | `{}` |+| `payment_source_id` | The saved payment source created after completion | `card_xyz789` |+| `payment_source_type` | The type of saved payment source | `Spree::CreditCard` |++### Payment Setup Session API++<Note>+Payment Setup Sessions require [customer authentication](/api-reference/store-api/authentication). The customer must be logged in.+</Note>++**Create a Payment Setup Session:**++```typescript+const options = { token: jwtToken }++// Create a setup session for saving a payment method+const setupSession = await client.customer.paymentSetupSessions.create({+ payment_method_id: 'pm_xyz789',+ external_data: {},+}, options)++// Use the client secret with the gateway's frontend SDK+console.log(setupSession.external_client_secret) // e.g. 'seti_ABC123_secret_xyz'+```++**Response shape (`StorePaymentSetupSession`):**++```json+{+ "id": "pss_abc123",+ "status": "pending",+ "external_id": "seti_ABC123",+ "external_client_secret": "seti_ABC123_secret_xyz",+ "external_data": {},+ "payment_method_id": "pm_xyz789",+ "payment_source_id": null,+ "payment_source_type": null,+ "customer_id": "cus_def456"+}+```++**Get a Payment Setup Session:**++```typescript+const session = await client.customer.paymentSetupSessions.get('pss_abc123', options)+```++**Complete a Payment Setup Session** (after the customer completes setup on the frontend using the gateway SDK and `external_client_secret`):++```typescript+const completed = await client.customer.paymentSetupSessions.complete(+ 'pss_abc123',+ { external_data: {} },+ options+)+console.log(completed.status) // 'completed'+console.log(completed.payment_source_id) // e.g. 'card_xyz789' - the saved payment method+```++Spree will verify the result with the provider and create a saved payment source (e.g., `Spree::CreditCard`) that can be used for future payments.++## Supported Gateways++Spree team maintains several payment gateway integrations. All of these gateways are **fully PCI compliant**, using native gateway SDKs, meaning no sensitive payment data is stored or processed through Spree.++<Card title="Stripe" href="/integrations/payments/stripe" icon="link">+ Stripe integration, supports all Stripe payment methods, including credit cards, bank transfers, Apple Pay, Google Pay, Klarna, Afterpay, and more. Also supports quick checkout.+</Card>++<Card title="Adyen" href="/integrations/payments/adyen" icon="link">+ Adyen integration, supports all Adyen payment methods, including credit cards, bank transfers, Apple Pay, Google Pay, Klarna, and more.+</Card>++<Card title="PayPal" href="/integrations/payments/paypal" icon="link">+ Native PayPal integration, supports PayPal, PayPal Credit, and PayPal Pay Later.+</Card>++## Payment Events++Spree publishes events throughout the payment lifecycle that you can subscribe to. For the delivered payload schemas of these events (e.g. `payment.paid`, `payment_session.completed`), see the [Webhooks & Events reference](/api-reference/webhooks-events):++### Payment Events+| Event | Description |+|-------|-------------|+| `payment.paid` | Payment was completed |+| `order.paid` | Order is fully paid |++### Payment Session Events+| Event | Description |+|-------|-------------|+| `payment_session.processing` | Session is being processed |+| `payment_session.completed` | Session completed successfully |+| `payment_session.failed` | Session processing failed |+| `payment_session.canceled` | Session was canceled |+| `payment_session.expired` | Session expired |++### Payment Setup Session Events+| Event | Description |+|-------|-------------|+| `payment_setup_session.completed` | Setup completed, payment source saved |+| `payment_setup_session.failed` | Setup failed |+| `payment_setup_session.canceled` | Setup was canceled |++See [Events](/v5/developer/core-concepts/events) for more details on subscribing to events.++## Related Documentation++- [Payments (Store SDK)](/v5/developer/sdk/store/payments) - SDK how-to for payment sessions, payments, and setup sessions+- [Build a Custom Payment Method](/v5/developer/how-to/custom-payment-method) - Step-by-step guide to creating your own payment gateway integration+- [Orders](/v5/developer/core-concepts/orders) - Order management and state machine+- [Checkout Customization](/v5/developer/customization/checkout) - Customizing the checkout flow+- [Events](/v5/developer/core-concepts/events) - Subscribe to payment events++## Key Services++| Service | Description |+|---------|-------------|+| `Spree::Carts::Complete` | Completes the order — validates, processes payments (if not already done), advances state machine. Used by both the `POST /carts/:id/complete` endpoint and the webhook handler. |+| `Spree::Payments::HandleWebhook` | Processes a normalized webhook event — creates Payment, marks session completed, calls `Carts::Complete`. |+| `Spree::Payments::HandleWebhookJob` | Background job that wraps `HandleWebhook` — enqueued by the webhook controller for async processing. |++Both `Carts::Complete` and `HandleWebhook` are registered in `Spree::Dependencies` and can be replaced with custom implementations:++```ruby+# config/initializers/spree.rb+Spree::Dependencies.carts_complete_service = 'MyApp::CustomCartComplete'+Spree::Dependencies.payments_handle_webhook_service = 'MyApp::CustomWebhookHandler'+```diff --git a/docs/v5/developer/core-concepts/pricing.mdx b/docs/v5/developer/core-concepts/pricing.mdxnew file mode 100644index 0000000000..4c22ed1929--- /dev/null+++ b/docs/v5/developer/core-concepts/pricing.mdx@@ -0,0 +1,357 @@+---+title: Pricing+description: Prices, Price Lists, Price Rules, and the Pricing Context — Spree's flexible pricing engine for regional, wholesale, volume, and market-based pricing.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/pricing"+---++import { Since } from '/snippets/since.mdx';++## Overview++Spree's pricing system supports both simple single-currency pricing and advanced multi-currency, rule-based pricing through Price Lists. Every [Variant](/v5/developer/core-concepts/products#variants) can have multiple prices — a base price per currency, plus additional prices from Price Lists that apply conditionally based on rules like geography, customer segment, or quantity.++## Prices++Each variant has one or more `Price` records — one per currency. The API automatically returns the correct price based on the current currency and [Market](/v5/developer/core-concepts/markets) context. See [monetary amounts](/api-reference/store-api/monetary-amounts) for how money fields (decimal, cents, and display string) are formatted across the API.++| Attribute | Description | Example |+|-----------|-------------|---------|+| `amount` | Current selling price | `"99.90"` |+| `compare_at_amount` | Original/compare price for strikethrough display | `"129.90"` |+| `currency` | ISO 4217 currency code | `USD` |++<Warning>+If a product doesn't have a price in the selected currency, it won't appear in Store API responses by default.+</Warning>++### Fetching Prices via API++The Store API returns the resolved price (including Price List rules) for the current currency and market context:++<CodeGroup>++```typescript Store SDK+// Product price is included by default+const product = await client.products.get('spree-tote')+console.log(product.price.amount) // "15.99" — resolved for current currency+console.log(product.price.compare_at_amount) // "19.99" — compare-at/strikethrough price (if set)++// Each variant has its own price+const detailed = await client.products.get('spree-tote', {+ expand: ['variants'],+})+detailed.variants?.forEach(variant => {+ console.log(variant.price.amount) // "15.99"+ console.log(variant.price.compare_at_amount) // "19.99"+})+```++```typescript Admin SDK+const product = await adminClient.products.get('prod_86Rf07xd4z', {+ expand: ['variants'],+})+```++```bash cURL+# Product price is always in the response+curl 'https://api.mystore.com/api/v3/store/products/spree-tote' \+ -H 'X-Spree-API-Key: pk_xxx'++# With variants+curl 'https://api.mystore.com/api/v3/store/products/spree-tote?expand=variants' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++### Setting Prices via the Admin API++Base prices are set per variant per currency. Use the [Admin API](/api-reference/admin-api/introduction) — via the [Admin SDK](/v5/developer/sdk/admin/quickstart) — to set them individually or in bulk (`bulk_upsert` matches on variant + currency):++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++// Set / change one variant's price in a currency+await client.prices.create({ variant_id: 'variant_xxx', currency: 'USD', amount: '15.99' })++// Upsert many at once+await client.prices.bulkUpsert({+ prices: [+ { variant_id: 'variant_xxx', currency: 'USD', amount: '15.99' },+ { variant_id: 'variant_xxx', currency: 'EUR', amount: '14.99' },+ ],+})+```++```bash CLI+spree api post /prices/bulk_upsert -d '{+ "prices": [+ { "variant_id": "variant_xxx", "currency": "USD", "amount": "15.99" },+ { "variant_id": "variant_xxx", "currency": "EUR", "amount": "14.99" }+ ]+}'+```++</CodeGroup>++## Price Lists <Since version="5.3" />++Price Lists allow you to create different pricing strategies based on various conditions. This enables advanced pricing scenarios like:++- **Market-based pricing** — different prices for different [Markets](/v5/developer/core-concepts/markets) (e.g., North America vs Europe)+- **Regional pricing** — different prices for different geographic zones+- **Wholesale/B2B pricing** — special prices for business customers+- **Volume discounts** — tiered pricing based on quantity purchased+- **Promotional pricing** — time-limited special offers+- **VIP customer pricing** — exclusive prices for specific customers++### How Price Lists Work++When a customer views a product, Spree's pricing resolver determines which price to use:++1. **Price List priority** — Price Lists are ordered by position; higher priority lists are checked first+2. **Status** — only `active` or `scheduled` Price Lists are considered+3. **Date range** — the current time must fall within `starts_at` and `ends_at` (if set)+4. **Price Rules** — all configured rules must match (or any, depending on `match_policy`)++If no applicable Price List is found, the base price is used.++### Price List Attributes++| Attribute | Description |+|-----------|-------------|+| `name` | Human-readable name for the Price List |+| `status` | `draft`, `active`, `scheduled`, or `inactive` |+| `starts_at` | Optional start date when the Price List becomes applicable |+| `ends_at` | Optional end date when the Price List stops being applicable |+| `match_policy` | How rules are evaluated: `all` (every rule must match) or `any` (at least one) |+| `position` | Priority order (lower numbers = higher priority) |++### Creating a Price List via the Admin API++Rules and per-variant price overrides ride on the create/update payload. Each rule is a `{ type, preferences }` draft (see [Price Rules](#price-rules) below):++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++const priceList = await client.priceLists.create({+ name: 'EU wholesale',+ match_policy: 'all',+ rules: [+ { type: 'customer_group_rule', preferences: { customer_group_ids: ['cg_xxx'] } },+ ],+ prices: [+ { variant_id: 'variant_xxx', currency: 'EUR', amount: '19.99' },+ ],+})++// Price Lists are draft until activated+await client.priceLists.activate(priceList.id)+```++```bash CLI+spree api post /price_lists -d '{+ "name": "EU wholesale",+ "match_policy": "all",+ "prices": [{ "variant_id": "variant_xxx", "currency": "EUR", "amount": "19.99" }]+}'+spree api patch /price_lists/pl_xxx/activate+```++</CodeGroup>++## Price Rules <Since version="5.3" />++Price Rules define conditions that must be met for a Price List to apply. Spree includes five built-in rule types:++| Rule | Description | Use Case |+|------|-------------|----------|+| **Market Rule** | Matches based on the current [Market](/v5/developer/core-concepts/markets) | Regional pricing across markets |+| **Zone Rule** | Matches based on the customer's geographic zone | Country or state-level pricing |+| **User Rule** | Matches specific customer accounts | VIP customers, wholesale accounts |+| **Customer Group Rule** | Matches members of customer groups | Loyalty tiers, membership pricing |+| **Volume Rule** | Matches based on quantity purchased | Bulk discounts, tiered pricing |++### Market Rule <Since version="5.4" />++The recommended approach for regional pricing when using Markets. Applies the Price List when the customer is in one of the specified markets.++**Example:** Price a product at $29.99 in North America and €24.99 in Europe, rather than relying on exchange rate conversion.++### Zone Rule++Applies based on the customer's geographic zone. Useful for regional or country-specific pricing when not using Markets.++### User Rule++Limits the Price List to specific customer accounts. Useful for VIP customers, employee pricing, or wholesale accounts.++### Customer Group Rule++Applies to members of specific customer groups. Useful for wholesale tiers, loyalty programs, or membership-based pricing.++### Volume Rule++Applies based on quantity purchased. Supports `min_quantity` and `max_quantity` to create tiered pricing:++| Tier | Quantity | Price |+|------|----------|-------|+| Base | 1–9 | $10.00 |+| Bulk Tier 1 | 10–49 | $8.50 |+| Bulk Tier 2 | 50+ | $7.00 |++<Info>+Custom Price Rules can be created for specialized pricing logic. See the [Customization Quickstart](/v5/developer/customization/quickstart) for details.+</Info>++## Pricing Context <Since version="5.3" />++When resolving prices, Spree considers the full context of the request:++| Context | Source | Description |+|---------|--------|-------------|+| Currency | Market or request header | The currency to price in |+| Market | Customer's country | The [Market](/v5/developer/core-concepts/markets) for market-based rules |+| Zone | Customer's address | The geographic zone for zone-based rules |+| Customer | JWT authentication | The logged-in customer for user-based rules |+| Quantity | Cart line item | The quantity for volume-based rules |+| Date | Current time | For time-based Price List scheduling |++The Store API automatically builds this context from the [request headers](/api-reference/store-api/localization) (`X-Spree-Currency`, `X-Spree-Country`) and authentication state. You don't need to construct it manually — just make API requests and the correct price is resolved.++<Info>+Price resolution runs per request — there is no in-process caching of resolved prices. The Store API instead relies on HTTP/CDN caching, with `Vary` headers keyed on the `X-Spree-Currency` and `X-Spree-Locale` request headers so each currency/locale combination is cached separately at the edge.+</Info>++## Time-Based Pricing++Price Lists support scheduling through `starts_at` and `ends_at` attributes. Scheduled Price Lists automatically become applicable when the current time falls within their date range — no manual activation needed.++**Example:** A Black Friday sale Price List with `starts_at: 2025-11-28 00:00` and `ends_at: 2025-11-28 23:59` will automatically activate and deactivate.++## Managing Price Lists++Price Lists are managed in the Admin Panel under **Products → Price Lists**, or via the Admin API.++Each Price List contains prices for specific variants and currencies. Products can be added to a Price List, and individual variant prices set within it.++## Price History (EU Omnibus Directive) <Since version="5.4" />++Spree automatically records price changes for EU Omnibus Directive compliance. When a product goes on sale, EU regulations require displaying the lowest price in the preceding 30 days alongside the discounted price.++### How It Works++Every time a base price amount changes, a `PriceHistory` record is created automatically. Price list prices are not tracked — only the base price visible to all customers.++### Fetching Prior Price via API++The prior price is available as an expandable field on product and variant endpoints:++<CodeGroup>++```typescript Store SDK+const product = await client.products.get('spree-tote', {+ expand: ['prior_price'],+})++if (product.prior_price) {+ console.log(product.prior_price.amount) // "9.99"+ console.log(product.prior_price.display_amount) // "$9.99"+ console.log(product.prior_price.currency) // "USD"+ console.log(product.prior_price.recorded_at) // "2026-03-10T..."+}+```++```typescript Admin SDK+const product = await adminClient.products.get('prod_86Rf07xd4z', {+ expand: ['prior_price'],+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products/spree-tote?expand=prior_price' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++The response includes a `prior_price` object when expanded:++```json+{+ "id": "prod_xxx",+ "name": "Spree Tote",+ "price": { "amount": "15.99", "currency": "USD", "display_amount": "$15.99" },+ "prior_price": {+ "amount": "9.99",+ "amount_in_cents": 999,+ "currency": "USD",+ "display_amount": "$9.99",+ "recorded_at": "2026-03-10T14:30:00Z"+ }+}+```++### Configuration++Price history tracking is enabled by default. To disable it (e.g., for non-EU stores):++```ruby+# config/initializers/spree.rb+Spree.config do |config|+ config.track_price_history = false+ config.price_history_retention_days = 30 # default+end+```++Price history retention defaults to 30 days and can be configured globally. A Rake task is provided for cleanup:++<CodeGroup>++```bash Spree CLI (Docker)+spree rake spree:price_history:prune+```++```bash Without Spree CLI+bundle exec rake spree:price_history:prune+```++</CodeGroup>++### Seeding Existing Prices++After enabling price history on an existing store, seed the current prices as a baseline:++<CodeGroup>++```bash Spree CLI (Docker)+spree rake spree:price_history:seed+```++```bash Without Spree CLI+bundle exec rake spree:price_history:seed+```++</CodeGroup>++## Related Documentation++- [Products](/v5/developer/core-concepts/products) — Products, Variants, and base prices+- [Store SDK: Products](/v5/developer/sdk/store/products) — Fetching product and variant prices with the Store SDK+- [Markets](/v5/developer/core-concepts/markets) — Geographic regions with currency and locale+- [Taxes](/v5/developer/core-concepts/taxes) — Tax categories, tax rates, and zones+- [Promotions](/v5/developer/core-concepts/promotions) — Discount-based pricing via promotion rulesdiff --git a/docs/v5/developer/core-concepts/products.mdx b/docs/v5/developer/core-concepts/products.mdxnew file mode 100644index 0000000000..228f757599--- /dev/null+++ b/docs/v5/developer/core-concepts/products.mdx@@ -0,0 +1,710 @@+---+title: Products+description: How Spree models products, variants, option types, images, prices, and categories — the building blocks of every catalog and storefront.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/products"+---++import { Since } from '/snippets/since.mdx';++## Overview++A product represents something you sell. Each product has one or more **variants** — the actual purchasable items with their own SKU, price, and inventory. For example, a "T-Shirt" product might have variants for each size and color combination.++Products are organized into **categories** — a flexible hierarchy for grouping products. Categories can be filtered, sorted, and searched via the Store API.++<Info>+Product names, descriptions, slugs, and SEO fields are [translatable](/v5/developer/core-concepts/translations#resource-translations).+</Info>++```mermaid+erDiagram+ Product ||--o{ Variant : "has many"+ Product }o--o{ OptionType : "has many"+ Product ||--o{ Classification : "has many"+ Variant ||--o{ Price : "has many"+ Variant ||--o{ StockItem : "has many"+ Variant ||--o{ Image : "has many"+ Variant }o--o{ OptionValue : "has many"+ OptionType ||--o{ OptionValue : "has many"+ Taxon ||--o{ Classification : "has many"+ Taxonomy ||--o{ Taxon : "has many"++ Product {+ string name+ string slug+ string status+ text description+ datetime available_on+ }++ Variant {+ string sku+ boolean is_master+ decimal weight+ }++ Price {+ decimal amount+ decimal compare_at_amount+ string currency+ }++ OptionType {+ string name+ string presentation+ }++ OptionValue {+ string name+ string presentation+ }+```++## Product Attributes++| Attribute | Description | Translatable |+|-----------|-------------|:---:|+| `name` | Product name | Yes |+| `description` | Full product description | Yes |+| `slug` | URL-friendly identifier (e.g., `spree-tote`) | Yes |+| `status` | `draft`, `active`, or `archived` | No |+| `available_on` | Date the product becomes available for sale | No |+| `discontinue_on` | Date the product is no longer available | No |+| `meta_title` | Custom SEO title | Yes |+| `meta_description` | SEO description | Yes |+| `meta_keywords` | SEO keywords | Yes |+| `purchasable` | Whether the product can be added to cart | No |+| `in_stock` | Whether any variant has stock available | No |+| `price` | Default variant's price in the current currency | No |+| `thumbnail_url` | URL to the product's first image — always returned, no expand needed | No |+| `tags` | Array of tag strings for filtering | No |++## Listing Products++<CodeGroup>++```typescript Store SDK+// List products with pagination+const { data: products, meta } = await client.products.list({+ limit: 12,+ page: 1,+})++// Filter by price range and availability+const filtered = await client.products.list({+ price_gte: 10,+ price_lte: 50,+ in_stock: true,+})++// Search by keyword+const results = await client.products.list({+ search: 'tote bag',+})++// Sort products+const sorted = await client.products.list({+ sort: '-price', // high to low; also: price, name, -name, available_on, -available_on, best_selling+})+```++```typescript Admin SDK+const { data: products, meta } = await adminClient.products.list({+ limit: 12,+ page: 1,+})+```++```bash cURL+# List products+curl 'https://api.mystore.com/api/v3/store/products?limit=12&page=1' \+ -H 'X-Spree-API-Key: pk_xxx'++# Filter by price and stock+curl 'https://api.mystore.com/api/v3/store/products?q[price_gte]=10&q[price_lte]=50&q[in_stock]=true' \+ -H 'X-Spree-API-Key: pk_xxx'++# Search+curl 'https://api.mystore.com/api/v3/store/products?q[search]=tote+bag' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++See [Querying](/api-reference/store-api/querying) for the full list of filtering, sorting, and pagination options.++## Getting a Product++<CodeGroup>++```typescript Store SDK+// Get by slug+const product = await client.products.get('spree-tote')++// Get with included relations+const detailed = await client.products.get('spree-tote', {+ expand: ['variants', 'media', 'option_types', 'categories'],+})+// detailed.variants => [{ id: "var_xxx", sku: "TOTE-S-R", price: { amount: "15.99", currency: "USD" }, ... }]+// detailed.media => [{ id: "img_xxx", original_url: "https://cdn...", position: 1 }]+// detailed.option_types => [{ name: "size", label: "Size", position: 1, kind: "..." }]+// detailed.option_values => [{ name: "small", label: "S", option_type_name: "size", ... }] // separate top-level array when expanded+```++```typescript Admin SDK+const product = await adminClient.products.get('prod_86Rf07xd4z')+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products/spree-tote?expand=variants,media,option_types,categories' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++Pass `expand` to include related resources in a single response — see [expand relations](/api-reference/store-api/relations) for how relation inclusion works.++## Managing Products++The examples above use the **Store API** (publishable key, read-only, customer-facing). To **create and manage** products, use the [Admin API](/api-reference/admin-api/introduction) — via the [Admin SDK](/v5/developer/sdk/admin/quickstart) or the [Spree CLI](/v5/developer/cli/admin-api).++A product's purchasable attributes (SKU, prices, stock) live on its **variants**, which you can create inline:++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++const product = await client.products.create({+ name: 'Premium T-Shirt',+ description: 'Soft, organic cotton.',+ status: 'active',+ variants: [+ {+ sku: 'TSHIRT-S-NAVY',+ options: [+ { name: 'size', value: 'Small' },+ { name: 'color', value: 'navy' },+ ],+ prices: [{ currency: 'USD', amount: '29.99' }],+ stock_items: [{ stock_location_id: 'sloc_xxx', count_on_hand: 50 }],+ },+ ],+})+```++```bash CLI+spree api post /products -d '{+ "name": "Premium T-Shirt",+ "status": "active",+ "variants": [{+ "sku": "TSHIRT-S-NAVY",+ "options": [{ "name": "size", "value": "Small" }],+ "prices": [{ "currency": "USD", "amount": "29.99" }]+ }]+}'+```++</CodeGroup>++Update, clone, or archive a product (deleting soft-deletes it):++<CodeGroup>++```typescript Admin SDK+await client.products.update('prod_xxx', { name: 'Premium Tee', status: 'active' })+await client.products.clone('prod_xxx') // duplicate as a new draft+await client.products.delete('prod_xxx') // soft-delete+```++```bash CLI+spree api patch /products/prod_xxx -d '{"name": "Premium Tee"}'+spree api post /products/prod_xxx/clone+spree api delete /products/prod_xxx+```++</CodeGroup>++<Tip>+Operating on many products at once? The Admin API has bulk actions — `bulkStatusUpdate`, `bulkAddToCategories`, `bulkAddTags`, `bulkDestroy`, and more. See the [Admin API endpoint index](/api-reference/admin-api/endpoints).+</Tip>++## Product Filters++Get available filter options for building a faceted search UI. Returns price ranges, option values, and categories with counts:++<CodeGroup>++```typescript Store SDK+const filters = await client.products.filters()+// {+// filters: [+// { id: "price", type: "price_range", min: 9.99, max: 199.99, currency: "USD" },+// { id: "availability", type: "availability", options: [{ id: "in_stock", count: 42 }] },+// { id: "opt_xxx", type: "option", name: "size", label: "Size", kind: "...",+// options: [{ id: "optv_xxx", name: "small", label: "Small", count: 12 }, ...] },+// { id: "categories", type: "category",+// options: [{ id: "ctg_xxx", name: "Clothing", permalink: "clothing", count: 45 }] },+// ],+// sort_options: [{ id: "price" }, ...],+// default_sort: "best_selling",+// total_count: 120,+// }++// Scoped to a specific category+const categoryFilters = await client.products.filters({+ category_id: 'ctg_xxx',+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products/filters' \+ -H 'X-Spree-API-Key: pk_xxx'++# Scoped to a category+curl 'https://api.mystore.com/api/v3/store/products/filters?category_id=ctg_xxx' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++## Variants++Variants are the purchasable units of a product. Each variant has its own SKU, price, inventory, and images, and is defined by a unique combination of option values.++| Attribute | Description |+|-----------|-------------|+| `sku` | Unique stock keeping unit |+| `barcode` | Barcode (UPC, EAN, etc.) |+| `price` | Price in the current currency |+| `original_price` | Compare-at price for showing discounts |+| `weight`, `height`, `width`, `depth` | Dimensions for shipping calculations |+| `in_stock` | Whether stock is available |+| `backorderable` | Whether the variant can be ordered when out of stock |+| `option_values` | The option values that define this variant (e.g., Size: Small, Color: Red) |++### Master Variant++Every product has a **master variant** that holds default pricing and inventory. If a product has no option types (e.g., a book with no size/color), the master variant is the only purchasable variant.++### Regular Variants++When a product has option types, each unique combination of option values creates a variant. For example, a T-shirt with sizes (S, M, L) and colors (Red, Green) has 6 variants:++| SKU | Size | Color |+|-----|------|-------|+| `TEE-S-R` | Small | Red |+| `TEE-S-G` | Small | Green |+| `TEE-M-R` | Medium | Red |+| `TEE-M-G` | Medium | Green |+| `TEE-L-R` | Large | Red |+| `TEE-L-G` | Large | Green |++The product's `default_variant_id` points to the first non-master variant (or the master variant if none exist).++Add a variant to an existing product via the Admin API (SKU, prices, and stock all live on the variant):++<CodeGroup>++```typescript Admin SDK+const variant = await client.products.variants.create('prod_xxx', {+ sku: 'TEE-L-R',+ options: [+ { name: 'size', value: 'Large' },+ { name: 'color', value: 'Red' },+ ],+ prices: [{ currency: 'USD', amount: '24.99' }],+ stock_items: [{ stock_location_id: 'sloc_xxx', count_on_hand: 30 }],+})+```++```bash CLI+spree api post /products/prod_xxx/variants -d '{+ "sku": "TEE-L-R",+ "options": [{ "name": "size", "value": "Large" }],+ "prices": [{ "currency": "USD", "amount": "24.99" }]+}'+```++</CodeGroup>++## Option Types and Option Values++Option types define the axes of variation for a product (e.g., Size, Color, Material). Option values are the specific choices within each type (e.g., Small, Medium, Large).++A product must have at least one option type to have multiple variants. Option types and their values are included in the product response when requested:++<CodeGroup>++```typescript Store SDK+const product = await client.products.get('spree-tee', {+ expand: ['option_types', 'option_values'],+})++// Option types describe the axes of variation+product.option_types?.forEach(optionType => {+ console.log(optionType.label) // "Size"+})++// Option values are a separate flat array; each carries its parent's id/label+product.option_values?.forEach(value => {+ console.log(value.option_type_label, value.label) // "Size", "Small"+})+```++```typescript Admin SDK+const product = await adminClient.products.get('prod_k5nR8xLq', {+ expand: ['variants'],+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products/spree-tee?expand=option_types,option_values' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++<Info>+Option type `name` and `label` fields are translatable.+</Info>++Create option types (and their values) via the Admin API. Sending `option_values` replaces the full set, so include every value you want to keep:++<CodeGroup>++```typescript Admin SDK+const optionType = await client.optionTypes.create({+ name: 'size',+ label: 'Size',+ option_values: [+ { name: 'small', label: 'Small', position: 1 },+ { name: 'medium', label: 'Medium', position: 2 },+ { name: 'large', label: 'Large', position: 3 },+ ],+})+```++```bash CLI+spree api post /option_types -d '{+ "name": "size",+ "label": "Size",+ "option_values": [+ { "name": "small", "label": "Small" },+ { "name": "medium", "label": "Medium" }+ ]+}'+```++</CodeGroup>++## Media++Media can be attached to the product (via the master variant) or to individual variants. When displaying a product, show the images for the selected variant, falling back to the product-level images.++### Thumbnails++Every product response includes a `thumbnail_url` field — the URL to the first image, ready to use without any expands. Similarly, each variant includes a `thumbnail_url` URL and an `media_count` counter.++Use these fields for product listing pages to avoid loading all images:++<CodeGroup>++```typescript Store SDK+// List products — thumbnail_url is always included+const { data: products } = await client.products.list({ limit: 12 })++products.forEach(product => {+ product.thumbnail_url // "https://cdn.../tote-front.jpg" — no expand needed+})+```++```typescript Admin SDK+const { data: products } = await adminClient.products.list({ limit: 12 })+```++```bash cURL+# thumbnail_url is always in the response — no ?expand needed+curl 'https://api.mystore.com/api/v3/store/products?limit=12' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++<Warning>+Avoid using `?expand=media` on listing pages. This loads **all** images for every product in the response, which is unnecessary when you only need a thumbnail. Use `thumbnail_url` instead and only expand full media on the product detail page.+</Warning>++### All Images++On the product detail page, expand `media` and `variants` to get the full set of images. Images are ordered by `position`:++<CodeGroup>++```typescript Store SDK+const product = await client.products.get('spree-tote', {+ expand: ['media', 'variants'],+})++// Product-level images (from master variant)+product.media // [{ original_url: "https://cdn.../tote-front.jpg", position: 1 }, ...]++// Each variant has its own thumbnail and media_count+product.variants?.forEach(variant => {+ variant.thumbnail_url // "https://cdn.../tote-red.jpg" — always available+ variant.media_count // 3 — quick check without loading media+ variant.media // full image array (only when ?expand=media)+})+```++```typescript Admin SDK+const product = await adminClient.products.get('prod_86Rf07xd4z', {+ expand: ['media'],+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products/spree-tote?expand=media,variants' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++| Field | Available on | Always returned | Description |+|-------|-------------|:---:|-------------|+| `thumbnail_url` | Product | Yes | URL to the product's first media |+| `thumbnail_url` | Variant | Yes | URL to the variant's first media |+| `media_count` | Variant | Yes | Number of media |+| `media` | Product, Variant | No | Full image array (requires `?expand=media`) |++## Prices++Each variant can have multiple prices — one per currency, plus additional prices from [Price Lists](/v5/developer/core-concepts/pricing) that apply conditionally based on market, geography, customer segment, or quantity.++The API automatically returns the correct price based on the current currency and market context:++| Field | Description |+|-------|-------------|+| `price` | Current selling price |+| `original_price` | Compare-at price (for showing strikethrough discounts) |++See the [Pricing](/v5/developer/core-concepts/pricing) guide for details on Price Lists, Price Rules, and market-specific pricing.++## Categories++Categories provide a flexible way to organize products into hierarchical trees. Internally, Spree uses Taxonomies (category trees) and Taxons (nodes within those trees), but the Store API exposes them simply as **Categories**.++For example:+- **Categories** → Clothing → T-Shirts, Dresses+- **Brands** → Nike, Adidas, Puma+- **Collections** → Summer 2025, Best Sellers++Products can belong to multiple categories.++<CodeGroup>++```typescript Store SDK+// List categories+const { data: categories } = await client.categories.list()++// Get a category by permalink+const category = await client.categories.get('clothing/shirts')++// List products in a category+const { data: products } = await client.categories.products.list('clothing/shirts', {+ limit: 12,+})+```++```typescript Admin SDK+const { data: categories } = await adminClient.categories.list()+```++```bash cURL+# List categories+curl 'https://api.mystore.com/api/v3/store/categories' \+ -H 'X-Spree-API-Key: pk_xxx'++# Get a category by permalink+curl 'https://api.mystore.com/api/v3/store/categories/clothing/shirts' \+ -H 'X-Spree-API-Key: pk_xxx'++# List products in a category+curl 'https://api.mystore.com/api/v3/store/categories/clothing/shirts/products?limit=12' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++<Info>+Category `name` and `description` fields are translatable.+</Info>++## Publications and Sales Channels <Since version="5.5" />++A product is visible on a [Channel](/v5/developer/core-concepts/channels) only when a `ProductPublication` record joins the two. Publications carry an optional time window so a product can be scheduled to go live and come down without code or manual toggles.++| Publication state | What customers see |+|---|---|+| No publication exists | Product is not on this channel — invisible |+| Publication has no dates set | Live now and indefinitely |+| `published_at` is in the future | Scheduled — not yet visible |+| `unpublished_at` is in the past | Hidden — was visible, now sunset |+| Within the window | Live |++Product `status` (`draft` / `active` / `archived`) is the **outer gate**: a Draft or Archived product is hidden on every channel regardless of its publication window. Only `active` products consult publication state.++### Reading publications++Publications appear in the API under `product_publications` when expanded; the same data is available through the `channels` association as a flat list of joined channels.++<CodeGroup>++```typescript Admin SDK+const product = await adminClient.products.get('prod_abc', {+ expand: ['product_publications', 'channels'],+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/admin/products/prod_abc?expand=product_publications,channels' \+ -H 'X-Spree-API-Key: sk_xxx'+```++</CodeGroup>++```json Response+{+ "data": {+ "id": "prod_abc",+ "status": "active",+ "channels": [+ { "id": "ch_online", "code": "online", "name": "Online Store" }+ ],+ "product_publications": [+ {+ "id": "pp_xyz",+ "channel_id": "ch_online",+ "published_at": "2026-07-01T00:00:00Z",+ "unpublished_at": null+ }+ ]+ }+}+```++### Writing publications++Two write surfaces serve different shapes:++- **Per-product, full-set** — `PATCH /api/v3/admin/products/{id}` with a `product_publications` array. The array represents the complete desired state; channels absent from the payload are detached.++ <CodeGroup>++ ```typescript Admin SDK+ await adminClient.products.update('prod_abc', {+ product_publications: [+ { channel_id: 'ch_online' },+ { channel_id: 'ch_pos', published_at: '2026-07-01T00:00:00Z' },+ ],+ })+ ```++ ```bash cURL+ curl -X PATCH 'https://api.mystore.com/api/v3/admin/products/prod_abc' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{+ "product_publications": [+ { "channel_id": "ch_online" },+ { "channel_id": "ch_pos", "published_at": "2026-07-01T00:00:00Z" }+ ]+ }'+ ```++ </CodeGroup>++- **Per-channel, bulk** — `POST /api/v3/admin/channels/{id}/add_products` and `POST /api/v3/admin/channels/{id}/remove_products` for publishing or unpublishing many products at once. Idempotent: re-publishing an already-published product is a no-op for its window unless `published_at` / `unpublished_at` are explicitly passed.++ <CodeGroup>++ ```typescript Admin SDK+ await adminClient.channels.addProducts('ch_online', {+ product_ids: ['prod_abc', 'prod_def'],+ published_at: '2026-07-01T00:00:00Z',+ })++ await adminClient.channels.removeProducts('ch_online', {+ product_ids: ['prod_abc'],+ })+ ```++ ```bash cURL+ curl -X POST 'https://api.mystore.com/api/v3/admin/channels/ch_online/add_products' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{+ "product_ids": ["prod_abc", "prod_def"],+ "published_at": "2026-07-01T00:00:00Z"+ }'++ curl -X POST 'https://api.mystore.com/api/v3/admin/channels/ch_online/remove_products' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{ "product_ids": ["prod_abc"] }'+ ```++ </CodeGroup>++The two surfaces converge on the same `spree_product_publications` table — pick whichever matches your call site.++### Listing products on a specific channel++Storefronts and `client.products.list()` calls return only products published on the resolved channel (live within the publication window, with the product itself `active`). To scope a Store SDK request to a non-default channel — e.g. a POS app querying for the POS catalog — set the channel `code` on the client or per-request:++<CodeGroup>++```typescript Store SDK+// Client-level default+const client = createClient({ baseUrl, publishableKey, channel: 'pos' })++// Per-request override+const posProducts = await client.products.list({}, { channel: 'pos' })+```++```typescript Admin SDK+// filter by the channel's code via Ransack (q[channels_code_eq])+const { data: products } = await adminClient.products.list({ channels_code_eq: 'pos' })+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Channel: pos'+```++</CodeGroup>++For Admin API filtering across channels (back-office reports, admin UI lists), use Ransack instead: `q[channels_id_in][]=ch_xxx`. See [Sales Channels](/v5/developer/core-concepts/channels) for the resolution rules.++### Auto-publish on the default channel++When a product is created via the dashboard, it is auto-published on the store's default channel (the only channel where `default = true`). The Admin API does **not** auto-publish — supply `product_publications: [{ channel_id }]` on create or call `add_products` afterwards.++See [Sales Channels](/v5/developer/core-concepts/channels) for the full channel lifecycle, including default-channel resolution and the `X-Spree-Channel` header.++## Related Documentation++- [Sales Channels](/v5/developer/core-concepts/channels) — Channels, publications, and order attribution+- [Pricing](/v5/developer/core-concepts/pricing) — Price Lists, Price Rules, and market-specific pricing+- [Inventory](/v5/developer/core-concepts/inventory) — Stock management and backorders+- [Media](/v5/developer/core-concepts/media) — Image management+- [Translations](/v5/developer/core-concepts/translations) — Translating product content+- [Search & Filtering](/v5/developer/core-concepts/search-filtering) — Full-text search and Ransack filtering+- [Store SDK Products](/v5/developer/sdk/store/products) — Listing, fetching, filtering, and categories via `client.products`+- [Querying](/api-reference/store-api/querying) — API filtering, sorting, and paginationdiff --git a/docs/v5/developer/core-concepts/promotions.mdx b/docs/v5/developer/core-concepts/promotions.mdxnew file mode 100644index 0000000000..29bef43651--- /dev/null+++ b/docs/v5/developer/core-concepts/promotions.mdx@@ -0,0 +1,386 @@+---+title: Promotions+description: Build percentage and fixed-amount discounts, free shipping, BOGO offers, and coupon codes with Spree's rule and action-based promotion system.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/promotions"+---++## Overview++Promotions within Spree are used to provide discounts to orders, offer free shipping, or add items at no extra cost (e.g., free gifts). The promotion system is highly flexible, allowing you to create complex promotional campaigns based on various conditions.++### Promotion Model Diagram++```mermaid+erDiagram+ Promotion {+ string name+ string description+ string kind+ string code+ string path+ datetime starts_at+ datetime expires_at+ integer usage_limit+ string match_policy+ boolean advertise+ }++ PromotionRule {+ string type+ text preferences+ }++ PromotionAction {+ string type+ integer position+ }++ CouponCode {+ string code+ string state+ }++ OrderPromotion {+ integer order_id+ integer promotion_id+ }++ Adjustment {+ decimal amount+ string label+ boolean eligible+ string state+ }++ Promotion ||--o{ PromotionRule : "has many"+ Promotion ||--o{ PromotionAction : "has many"+ Promotion ||--o{ CouponCode : "has many"+ Promotion ||--o{ OrderPromotion : "has many"+ Promotion }o--o{ Store : "available in"+ PromotionRule }o--o{ Product : "applies to"+ PromotionRule }o--o{ Taxon : "applies to"+ PromotionRule }o--o{ User : "applies to"+ PromotionAction ||--o{ Adjustment : "creates"+ PromotionAction ||--|| Calculator : "has one"+ Order ||--o{ OrderPromotion : "has many"+ CouponCode }o--o| Order : "used by"+```++**Key relationships:**+- **Promotion** defines the campaign with rules and actions+- **Promotion Rules** determine eligibility conditions (FirstOrder, ItemTotal, Taxon, etc.)+- **Promotion Actions** define what happens when applied (discount, free shipping, free items)+- **Coupon Codes** track usage for code-based promotions+- **[Adjustments](/v5/developer/core-concepts/adjustments)** are created on orders/line items to apply discounts++Promotions can be activated in two ways:++- **Automatic promotions** - Applied automatically when eligibility rules are met (e.g., free shipping on orders over $50)+- **Coupon code promotions** - Applied when a customer enters a valid code during checkout++Promotions consist of two main components:++- **Rules** - Conditions that must be met for the promotion to apply+- **Actions** - What happens when the promotion is applied (discount, free shipping, etc.)++## Promotion Attributes++| Attribute | Description | Example |+|-----------|-------------|---------|+| `name` | The name of the promotion | Summer Sale |+| `description` | Brief description (max 255 chars) | 20% off all summer items |+| `kind` | Type: `coupon_code` or `automatic` | `automatic` |+| `starts_at` | When the promotion becomes active | 2025-06-01 00:00:00 |+| `expires_at` | When the promotion expires | 2025-09-01 23:59:59 |+| `usage_limit` | Max times the promotion can be used | 500 |+| `match_policy` | How rules are evaluated: `all` or `any` | `all` |+| `advertise` | Whether to display on storefront | `true` |+| `path` | SEO-friendly URL path | `summer-sale` |++### Multi-Code Promotions++For promotions that need unique codes per customer (e.g., influencer campaigns), Spree supports bulk code generation:++| Attribute | Description | Example |+|-----------|-------------|---------|+| `multi_codes` | Enable bulk code generation | `true` |+| `number_of_codes` | How many codes to generate | 1000 |+| `code_prefix` | Prefix for generated codes | `SUMMER` |++Generated codes follow the pattern `{prefix}{random}`, e.g., `SUMMER22A0F62A230BD919`.++## Rules++Rules determine when a promotion is eligible. You can combine multiple rules and configure whether **all** rules must match or **any** rule is sufficient (via `match_policy`).++### FirstOrder++Applies only to a customer's first order. Checks both user account and email address to prevent abuse.++**Use case:** Welcome discount for new customers.++### ItemTotal++Requires the order subtotal to meet minimum and/or maximum thresholds.++**Configuration:**+- `preferred_amount_min` - Minimum order amount (default: 100.00)+- `preferred_operator_min` - Comparison operator: `gt` (greater than) or `gte` (greater than or equal)+- `preferred_amount_max` - Maximum order amount (optional)+- `preferred_operator_max` - Comparison operator: `lt` (less than) or `lte` (less than or equal)++**Use case:** "Free shipping on orders over $50", "10% off orders between $100-$500".++### Product++Requires specific products to be in the order.++**Configuration:**+- `preferred_match_policy`:+ - `any` - At least one of the specified products+ - `all` - All specified products must be present+ - `none` - None of the specified products (exclusion)++**Use case:** "Buy Product A and get 20% off", "Discount excludes sale items".++### Taxon++Requires products from specific categories (taxons) to be in the order.++**Configuration:**+- `preferred_match_policy`: `any` or `all`++The rule automatically includes products in child taxons when a parent taxon is selected.++**Use case:** "20% off Electronics", "Buy from Shoes category get 10% off".++### User++Limits the promotion to specific customer accounts.++**Use case:** Employee discounts, VIP customer promotions.++### UserLoggedIn++Requires the customer to be logged in with an account.++**Use case:** Member-only discounts.++### OneUsePerUser++Ensures each customer can only use the promotion once.++**Use case:** One-time welcome offers, limited redemption campaigns.++### Country++Limits the promotion to orders shipping to a specific country.++**Configuration:**+- `preferred_country_id` or `preferred_country_iso` (ISO 2-letter code)++**Use case:** Regional promotions, country-specific campaigns.++### Currency++Limits the promotion to orders in a specific currency.++**Configuration:**+- `preferred_currency` - Currency code (e.g., "USD", "EUR")++**Use case:** Currency-specific pricing strategies.++### OptionValue++Requires products with specific option values (e.g., size, color) to be in the order.++**Configuration:**+- `preferred_eligible_values` - Array of `Spree::OptionValueVariant` IDs (the option-value↔variant join records the rule matches against the order's variants), not variant IDs++**Use case:** "10% off all red items", "Discount on size XL".++### CustomerGroup++Limits the promotion to customers belonging to specific customer groups.++**Configuration:**+- `preferred_customer_group_ids` - Array of customer group IDs++Customer groups are managed in Admin > Customers > Customer Groups and allow you to segment customers for targeted promotions.++**Use case:** VIP programs, loyalty tiers, wholesale pricing, B2B customer segments.++## Actions++Actions define what happens when a promotion is applied.++### CreateAdjustment++Creates a discount on the entire order total.++**Default calculator:** `FlatPercentItemTotal` (percentage off order)++**Available calculators:**+- `FlatPercentItemTotal` - Percentage off the order total+- `FlatRate` - Fixed amount off+- `FlexiRate` - First item at one rate, additional items at another+- `TieredFlatRate` - Different rates based on order total tiers+- `TieredPercent` - Different percentages based on order total tiers++**Use case:** "10% off your order", "$20 off orders over $100".++### CreateItemAdjustments++Creates discounts on individual line items. Only applies to items that match the promotion rules (e.g., items in a specific category).++**Default calculator:** `PercentOnLineItem` (percentage off each item)++The action respects rule actionability - if a Taxon rule specifies "Electronics", only electronics items receive the discount.++**Use case:** "15% off shoes", "Buy 2+ shirts get 10% off each".++### FreeShipping++Makes all shipments free by creating negative adjustments equal to shipping costs.++**Use case:** "Free shipping on orders over $75", "Free shipping with code FREESHIP".++### CreateLineItems++Automatically adds specified products to the cart when the promotion is eligible.++**Configuration:**+- Map of variant IDs to quantities to add++The action checks stock availability before adding items. Items are not automatically removed if eligibility is lost - customers must remove them manually.++**Use case:** "Free gift with purchase", "Buy 2 get 1 free", "Spend $100 get free sample".++## Managing Promotions++Create and manage promotions via the [Admin API](/api-reference/admin-api/introduction). Rules and actions can be supplied inline on create — each is a `{ type, preferences }` draft using the rule/action types described above:++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++// "20% off orders over $100 with code SUMMER20"+const promotion = await client.promotions.create({+ name: 'Summer Sale',+ code: 'SUMMER20',+ kind: 'coupon_code',+ rules: [{ type: 'item_total', preferences: { amount_min: 100 } }],+ actions: [+ {+ type: 'create_adjustment',+ calculator: { type: 'flat_percent_item_total', preferences: { flat_percent: 20 } },+ },+ ],+})+```++```bash CLI+spree api post /promotions -d '{+ "name": "Summer Sale",+ "code": "SUMMER20",+ "kind": "coupon_code",+ "rules": [{ "type": "item_total", "preferences": { "amount_min": 100 } }]+}'+```++</CodeGroup>++You can also add rules and actions to an existing promotion, or update and remove the promotion itself:++<CodeGroup>++```typescript Admin SDK+await client.promotions.rules.create('promo_xxx', {+ type: 'first_order',+})+await client.promotions.update('promo_xxx', { expires_at: '2026-09-01T00:00:00Z' })+await client.promotions.delete('promo_xxx')+```++```bash CLI+spree api post /promotions/promo_xxx/promotion_rules -d '{"type": "first_order"}'+spree api patch /promotions/promo_xxx -d '{"expires_at": "2026-09-01T00:00:00Z"}'+```++</CodeGroup>++## Coupon Codes++Coupon codes track promotion usage and can be single-use or multi-use.++### Single Code Promotions++Set the `code` attribute directly on the promotion. The `usage_limit` controls how many times it can be redeemed.++### Multi-Code Promotions++For bulk-generated codes, each code tracks its usage state:++| Attribute | Description | Example |+|-----------|-------------|---------|+| `code` | The unique code | `SUMMER22A0F62A230BD919` |+| `state` | Usage state | `unused`, `used` |++## Applying Coupon Codes via Store API++Customers [apply coupon codes during checkout](/v5/developer/sdk/store/cart-checkout) via the Store API:++<CodeGroup>++```typescript Store SDK+// Apply a discount code to the cart+const cart = await client.carts.discountCodes.apply('cart_abc123', 'SUMMER20', {+ spreeToken: '<token>',+})++// Remove a discount code from the cart+await client.carts.discountCodes.remove('cart_abc123', 'SUMMER20', {+ spreeToken: '<token>',+})+```++```bash cURL+# Apply a coupon code+curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_abc123/discount_codes' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Token: <token>' \+ -H 'Content-Type: application/json' \+ -d '{ "code": "SUMMER20" }'+```++</CodeGroup>++Automatic promotions are applied without any customer action — they are evaluated on every order update.++## Promotion Flow++How promotions are evaluated and applied:++1. **Order Update** — When an order is updated, the system checks all eligible promotions+2. **Eligibility Check** — For each promotion:+ - Check if within `starts_at` and `expires_at` range+ - Check if under `usage_limit`+ - Evaluate all rules based on `match_policy` (all or any)+3. **Action Execution** — If eligible, each action is applied+4. **Tracking** — Applied promotions are recorded on the order+5. **Re-evaluation** — Eligibility is re-checked on every order update; adjustments from ineligible promotions are removed++## Related Documentation++- [Build Custom Promotion Rules & Actions](/v5/developer/how-to/custom-promotion) - Step-by-step guide to creating custom rules and actions+- [Calculators](/v5/developer/core-concepts/calculators) - Learn about promotion calculators+- [Orders](/v5/developer/core-concepts/orders) - Understanding order processing+- [Customization Quickstart](/v5/developer/customization/quickstart) - Overview of customization options+- [Admin SDK Resources](/v5/developer/sdk/admin/resources) - The `client.promotions.*` resource-client pattern used in the examples above+- [Spree CLI Admin API](/v5/developer/cli/admin-api) - The `spree api` command reference for the CLI examples abovediff --git a/docs/developer/core-concepts/reports.mdx b/docs/v5/developer/core-concepts/reports.mdxsimilarity index 93%rename from docs/developer/core-concepts/reports.mdxrename to docs/v5/developer/core-concepts/reports.mdxindex dfe3c0e34e..480ae6161b 100644--- a/docs/developer/core-concepts/reports.mdx+++ b/docs/v5/developer/core-concepts/reports.mdx@@ -1,5 +1,6 @@---title: Reports+canonical: "https://spreecommerce.org/docs/v5/developer/core-concepts/reports"---## Overview@@ -202,7 +203,7 @@ can :manage, Spree::Report## Related Documentation-- [Build a Custom Report](/developer/how-to/custom-report) - Step-by-step guide to creating custom reports-- [Events](/developer/core-concepts/events) - How report generation uses the events system-- [Imports & Exports](/developer/core-concepts/imports-exports) - The broader async-export, ActiveStorage-attachment pattern reports share+- [Build a Custom Report](/v5/developer/how-to/custom-report) - Step-by-step guide to creating custom reports+- [Events](/v5/developer/core-concepts/events) - How report generation uses the events system+- [Imports & Exports](/v5/developer/core-concepts/imports-exports) - The broader async-export, ActiveStorage-attachment pattern reports share- [Admin API Endpoints](/api-reference/admin-api/endpoints) - Endpoints for creating and downloading reports from an integrationdiff --git a/docs/v5/developer/core-concepts/search-filtering.mdx b/docs/v5/developer/core-concepts/search-filtering.mdxnew file mode 100644index 0000000000..1b19a507ff--- /dev/null+++ b/docs/v5/developer/core-concepts/search-filtering.mdx@@ -0,0 +1,318 @@+---+title: Search & Filtering+description: "Use Ransack-style query parameters to search, filter, sort, and paginate products, taxons, and other resources through the Spree Store API."+canonical: "https://spreecommerce.org/docs/developer/core-concepts/search-filtering"+---++import { Since } from '/snippets/since.mdx';++## Overview++Spree provides powerful search, filtering, and sorting capabilities for products and other resources. The Store API supports:++- Full-text search across product names, SKUs, and searchable product metafields+- Attribute-based filtering (price range, availability, stock status)+- Category and taxon filtering+- Faceted search with filter counts+- Flexible sorting options (including sortable product custom fields via `sort=cf_{namespace}_{key}`)++## Product Search++Use the `search` parameter for full-text search across product fields:++<CodeGroup>++```typescript Store SDK+const { data: products } = await client.products.list({+ search: 'tote bag',+ limit: 12,+})+```++```typescript Admin SDK+const { data: products } = await adminClient.products.list({+ search: 'tote bag',+ limit: 12,+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products?q[search]=tote+bag&limit=12' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++## Filtering Products++### By Price Range++<CodeGroup>++```typescript Store SDK+const { data: products } = await client.products.list({+ price_gte: 20,+ price_lte: 100,+})+```++```typescript Admin SDK+const { data: products } = await adminClient.products.list({+ price_gte: 20,+ price_lte: 100,+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products?q[price_gte]=20&q[price_lte]=100' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++### By Availability++<CodeGroup>++```typescript Store SDK+const { data: products } = await client.products.list({+ in_stock: true,+})+```++```typescript Admin SDK+const { data: products } = await adminClient.products.list({+ in_stock: true,+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products?q[in_stock]=true' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++### By Category++<CodeGroup>++```typescript Store SDK+// Filter by category ID (includes descendants)+const { data: products } = await client.products.list({+ in_category: 'ctg_xxx',+})++// Multiple categories (OR logic, checkbox filters)+const { data: products } = await client.products.list({+ in_categories: ['ctg_shirts', 'ctg_pants'],+})+```++```typescript Admin SDK+// Filter by category ID (includes descendants)+const { data: products } = await adminClient.products.list({+ in_category: 'ctg_xxx',+})++// Multiple categories (OR logic)+const { data: products } = await adminClient.products.list({+ in_categories: ['ctg_shirts', 'ctg_pants'],+})+```++```bash cURL+# Filter by category ID (includes descendants)+curl 'https://api.mystore.com/api/v3/store/products?q[in_category]=ctg_xxx' \+ -H 'X-Spree-API-Key: pk_xxx'++# Multiple categories (OR logic)+curl 'https://api.mystore.com/api/v3/store/products?q[in_categories][]=ctg_shirts&q[in_categories][]=ctg_pants' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++### By Tags++<CodeGroup>++```typescript Store SDK+const { data: products } = await client.products.list({+ tags_name_cont: 'sale',+})+```++```typescript Admin SDK+const { data: products } = await adminClient.products.list({+ tags_name_cont: 'sale',+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products?q[tags_name_cont]=sale' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++## Sorting++<CodeGroup>++```typescript Store SDK+// Sort by price (low to high)+const sorted = await client.products.list({+ sort: 'price',+})++// Available sort options (prefix '-' for descending; use '-available_on' for newest):+// price, -price, name, -name, available_on, -available_on, best_selling+// Plus any product custom field marked sortable, e.g. cf_custom_label / -cf_custom_label+```++```typescript Admin SDK+const { data: products } = await adminClient.products.list({+ sort: 'price',+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products?sort=price' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++## Product Filters (Faceted Search)++Get available filter options for building a faceted search UI. Returns an array of typed filter objects (price range, availability, option types, categories) with counts, plus sort and pagination metadata:++<CodeGroup>++```typescript Store SDK+const filters = await client.products.filters()+// {+// filters: [+// { id: 'price', type: 'price_range', min: 9.99, max: 199.99, currency: 'USD' },+// { id: 'availability', type: 'availability', options: [{ id: 'in_stock', count: 42 }, { id: 'out_of_stock', count: 3 }] },+// { id: 'optt_xxx', type: 'option', name: 'size', label: 'Size', kind: 'dropdown', options: [{ id: 'optval_xxx', name: 'Small', label: 'Small', position: 1, color_code: null, image_url: null, count: 12 }] },+// { id: 'categories', type: 'category', options: [{ id: 'ctg_xxx', name: 'Clothing', permalink: 'clothing', count: 45 }] },+// ],+// sort_options: [{ id: 'manual' }, { id: 'price' }, { id: '-price' }],+// default_sort: 'manual',+// total_count: 120,+// }++// Scoped to a specific category+const categoryFilters = await client.products.filters({+ category_id: 'ctg_xxx',+})+```++```bash cURL+# All filters+curl 'https://api.mystore.com/api/v3/store/products/filters' \+ -H 'X-Spree-API-Key: pk_xxx'++# Scoped to a category+curl 'https://api.mystore.com/api/v3/store/products/filters?category_id=ctg_xxx' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++## Filtering Other Resources++The Store API uses query parameters prefixed with `q[]` for filtering any resource collection. Common filter predicates:++### Equality Predicates++| Predicate | Description | Example |+|-----------|-------------|---------|+| `eq` | Equals | `q[status_eq]=active` |+| `not_eq` | Not equals | `q[status_not_eq]=archived` |+| `in` | In array | `q[id_in][]=1&q[id_in][]=2` |++### String Predicates++| Predicate | Description | Example |+|-----------|-------------|---------|+| `cont` | Contains | `q[name_cont]=shirt` |+| `start` | Starts with | `q[name_start]=spree` |+| `end` | Ends with | `q[email_end][email protected]` |+| `i_cont` | Case-insensitive contains | `q[name_i_cont]=SHIRT` |++### Comparison Predicates++| Predicate | Description | Example |+|-----------|-------------|---------|+| `gt` | Greater than | `q[price_gt]=50` |+| `gteq` | Greater than or equal | `q[quantity_gteq]=10` |+| `lt` | Less than | `q[price_lt]=100` |+| `lteq` | Less than or equal | `q[created_at_lteq]=2025-12-31` |++### NULL Predicates++| Predicate | Description | Example |+|-----------|-------------|---------|+| `null` | Is NULL | `q[deleted_at_null]=true` |+| `not_null` | Is not NULL | `q[published_at_not_null]=true` |+| `present` | Is not NULL and not empty | `q[image_present]=true` |++<Info>+Only attributes explicitly allowed by each resource can be used for filtering. Attempting to filter on unsupported fields will be silently ignored.+</Info>++## Pagination++All list endpoints support pagination:++<CodeGroup>++```typescript Store SDK+const { data: products, meta } = await client.products.list({+ page: 1,+ limit: 24,+})+// meta.count => 150+// meta.pages => 7+```++```typescript Admin SDK+const { data: products, meta } = await adminClient.products.list({+ page: 1,+ limit: 24,+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/products?page=1&limit=24' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++See [Querying](/api-reference/store-api/querying) for the full list of filtering, sorting, and pagination options.++## Search Providers <Since version="5.4" />++Spree uses a pluggable search provider architecture. The default provider uses SQL (ILIKE + Ransack). For production catalogs with 1,000+ products, we recommend switching to [Meilisearch](/integrations/search/meilisearch) for typo tolerance, relevance ranking, and faster faceted search.++```ruby+# config/initializers/spree.rb+Spree.search_provider = 'Spree::SearchProvider::Meilisearch'+```++No client-side or API changes are needed — the same `q[search]`, filter params, and sort options work with any provider.++See [Build a Custom Search Provider](/v5/developer/how-to/custom-search-provider) for architecture details and how to build custom providers.++## Related Documentation++- [Products](/v5/developer/core-concepts/products) — Product catalog and listing+- [Store SDK Products](/v5/developer/sdk/store/products) — `client.products.list()` options and methods+- [Querying](/api-reference/store-api/querying) — Store API filtering, sorting, and pagination reference+- [Admin API querying](/api-reference/admin-api/querying) — Admin API filtering, sorting, and pagination reference+- [Build a Custom Search Provider](/v5/developer/how-to/custom-search-provider) — Step-by-step guide+- [Meilisearch Integration](/integrations/search/meilisearch) — Setup guidediff --git a/docs/developer/core-concepts/shipments.mdx b/docs/v5/developer/core-concepts/shipments.mdxsimilarity index 86%rename from docs/developer/core-concepts/shipments.mdxrename to docs/v5/developer/core-concepts/shipments.mdxindex 5f74041319..fd34aaddd7 100644--- a/docs/developer/core-concepts/shipments.mdx+++ b/docs/v5/developer/core-concepts/shipments.mdx@@ -1,13 +1,14 @@---title: Shipmentsdescription: How Spree models shipments, shipping methods, calculators, stock locations, split shipments, and the fulfillment workflow from order to delivery.+canonical: "https://spreecommerce.org/docs/v5/developer/core-concepts/shipments"---import { Since } from '/snippets/since.mdx';## Overview-A shipment represents a package being sent to a customer from a [Stock Location](/developer/core-concepts/inventory#stock-locations). Each order can have one or more shipments — Spree automatically splits orders into multiple shipments when items need to ship from different locations or require different shipping methods.+A shipment represents a package being sent to a customer from a [Stock Location](/v5/developer/core-concepts/inventory#stock-locations). Each order can have one or more shipments — Spree automatically splits orders into multiple shipments when items need to ship from different locations or require different shipping methods.```mermaiderDiagram@@ -43,10 +44,10 @@ erDiagram```**Key relationships:**-- **Shipment** tracks delivery of items from a [Stock Location](/developer/core-concepts/inventory#stock-locations)+- **Shipment** tracks delivery of items from a [Stock Location](/v5/developer/core-concepts/inventory#stock-locations)- **Shipping Method** defines the carrier/service (UPS, FedEx, etc.)- **Shipping Rate** represents the calculated cost for a method-- **[Zone](/developer/core-concepts/addresses#zones)** defines geographic regions for shipping availability+- **[Zone](/v5/developer/core-concepts/addresses#zones)** defines geographic regions for shipping availability- **Shipping Category** groups products with similar shipping requirements## Shipment Attributes@@ -84,7 +85,7 @@ The Store API/SDK exposes shipments as `fulfillments` with these attributes:## Selecting Shipping Rates-During checkout, after the customer provides a shipping address, Spree calculates available shipping rates for each shipment. The customer must select a rate before proceeding. See the [Cart & Checkout SDK](/developer/sdk/store/cart-checkout) guide for the full storefront cart and fulfillment flow.+During checkout, after the customer provides a shipping address, Spree calculates available shipping rates for each shipment. The customer must select a rate before proceeding. See the [Cart & Checkout SDK](/v5/developer/sdk/store/cart-checkout) guide for the full storefront cart and fulfillment flow.<CodeGroup>@@ -129,9 +130,9 @@ curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx/fulfillments/Shipping methods represent the carrier services available to customers (e.g., UPS Ground, FedEx Overnight, DHL International). Each shipping method is scoped to:-- **[Zones](/developer/core-concepts/addresses#zones)** — geographic regions where the method is available+- **[Zones](/v5/developer/core-concepts/addresses#zones)** — geographic regions where the method is available- **Shipping Categories** — product groups the method handles-- **[Stores](/developer/core-concepts/stores)** — which stores offer this method+- **[Stores](/v5/developer/core-concepts/stores)** — which stores offer this methodOnly methods whose zone matches the customer's shipping address are offered at checkout.@@ -148,7 +149,7 @@ Each product is assigned a shipping category. Shipping methods can be restricted### Calculators-Each shipping method uses a [Calculator](/developer/core-concepts/calculators) to determine the cost. Spree includes these built-in calculators:+Each shipping method uses a [Calculator](/v5/developer/core-concepts/calculators) to determine the cost. Spree includes these built-in calculators:| Calculator | Description ||------------|-------------|@@ -158,11 +159,11 @@ Each shipping method uses a [Calculator](/developer/core-concepts/calculators) t| Flexible rate | One rate for the first item, another for each additional || Price sack | Tiered pricing based on order total |-You can create custom calculators for more complex pricing. See the [Calculators guide](/developer/core-concepts/calculators).+You can create custom calculators for more complex pricing. See the [Calculators guide](/v5/developer/core-concepts/calculators).## Order Routing <Since version="5.5" />-When an order moves from cart to checkout, Spree decides which [Stock Location](/developer/core-concepts/inventory#stock-locations) fulfills it. **Order Routing** is the system that makes that decision — driven by configurable rules so merchants can express preferences like "fulfill from the customer's preferred warehouse first," "minimize the number of split shipments," or "always pick the closest location."+When an order moves from cart to checkout, Spree decides which [Stock Location](/v5/developer/core-concepts/inventory#stock-locations) fulfills it. **Order Routing** is the system that makes that decision — driven by configurable rules so merchants can express preferences like "fulfill from the customer's preferred warehouse first," "minimize the number of split shipments," or "always pick the closest location."```mermaidflowchart LR@@ -205,7 +206,7 @@ Routing happens **after** stock reservations: by the time routing runs, the cartFor business-specific logic — proximity to the shipping address, customer-tier-aware fulfillment, refrigerated SKUs, day-of-week dispatch — you write a custom **rule** that plugs into the existing pipeline. For replacing the algorithm entirely (OMS delegation, ML-based routing, multi-order optimization solvers), you write a custom **strategy**.-See the [Build Custom Order Routing](/developer/how-to/custom-order-routing) guide for both.+See the [Build Custom Order Routing](/v5/developer/how-to/custom-order-routing) guide for both.## Split Shipments@@ -268,7 +269,7 @@ The order matters — each splitter's output is the next one's input.### Extending Splitters-To add custom splitting logic — refrigerated SKUs, gift wrap separation, bulky-vs-small bin separation, anything that needs to fan one location's allocation into multiple shipments — write a new subclass of `Spree::Stock::Splitter::Base`. See the [Build Custom Stock Splitter](/developer/how-to/custom-stock-splitter) guide.+To add custom splitting logic — refrigerated SKUs, gift wrap separation, bulky-vs-small bin separation, anything that needs to fan one location's allocation into multiple shipments — write a new subclass of `Spree::Stock::Splitter::Base`. See the [Build Custom Stock Splitter](/v5/developer/how-to/custom-stock-splitter) guide.## Examples@@ -298,10 +299,10 @@ A store shipping from 2 locations (New York, Los Angeles) with 3 carriers and 3## Related Documentation-- [Orders](/developer/core-concepts/orders) — Checkout flow and shipping rate selection-- [Inventory](/developer/core-concepts/inventory) — Stock locations and inventory management-- [Calculators](/developer/core-concepts/calculators) — Shipping rate calculators-- [Addresses](/developer/core-concepts/addresses) — Shipping address and zones-- [Build Custom Order Routing](/developer/how-to/custom-order-routing) — Custom rules and strategies for choosing the fulfillment location-- [Events](/developer/core-concepts/events) — Subscribe to shipment events (e.g., `shipment.shipped`)+- [Orders](/v5/developer/core-concepts/orders) — Checkout flow and shipping rate selection+- [Inventory](/v5/developer/core-concepts/inventory) — Stock locations and inventory management+- [Calculators](/v5/developer/core-concepts/calculators) — Shipping rate calculators+- [Addresses](/v5/developer/core-concepts/addresses) — Shipping address and zones+- [Build Custom Order Routing](/v5/developer/how-to/custom-order-routing) — Custom rules and strategies for choosing the fulfillment location+- [Events](/v5/developer/core-concepts/events) — Subscribe to shipment events (e.g., `shipment.shipped`)- [Admin API](/api-reference/admin-api/introduction) — Inspect and manage shipments, shipping methods, and categories from the back officediff --git a/docs/v5/developer/core-concepts/slugs.mdx b/docs/v5/developer/core-concepts/slugs.mdxnew file mode 100644index 0000000000..a08d7b61d6--- /dev/null+++ b/docs/v5/developer/core-concepts/slugs.mdx@@ -0,0 +1,125 @@+---+title: Slugs+description: How Spree generates SEO-friendly URL slugs for products, categories, and stores, and how to look up resources by slug or ID via the API.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/slugs"+---++## Overview++Spree generates SEO-friendly URL slugs for resources like products, categories, and stores. Instead of accessing resources by ID, you can use clean, readable URLs based on resource names.++The Store API accepts slugs or prefixed IDs interchangeably for resource lookups. The Admin API resolves resources by prefixed ID only — slugs are not accepted.++<CodeGroup>++```typescript Store SDK+// Both work — slug or ID+const product = await client.products.get('spree-tote')+const product = await client.products.get('prod_86Rf07xd4z')++// Categories use permalink slugs+const category = await client.categories.get('clothing/shirts')+```++```typescript Admin SDK+// Admin SDK accepts prefixed IDs only — not slugs+const product = await adminClient.products.get('prod_86Rf07xd4z')+```++```bash cURL+# By slug+curl 'https://api.mystore.com/api/v3/store/products/spree-tote' \+ -H 'X-Spree-API-Key: pk_xxx'++# By ID+curl 'https://api.mystore.com/api/v3/store/products/prod_86Rf07xd4z' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++## Slug Generation++Slugs are automatically generated from resource names:++| Input | Generated Slug |+|-------|---------------|+| `Spree T-Shirt` | `spree-t-shirt` |+| `Café & Restaurant` | `cafe-and-restaurant` |+| `Summer Collection 2025` | `summer-collection-2025` |++If a slug already exists, Spree appends the SKU or a unique identifier to ensure uniqueness.++## Models with Slugs++| Resource | Slug Column | Translatable | Hierarchical |+|----------|-------------|:---:|:---:|+| Product | `slug` | Yes | No |+| Category | `permalink` | Yes | Yes |+| Store | `code` | No | No |++### Category Permalinks++Category slugs include the full parent path, making them hierarchical:++```+clothing → "clothing"+clothing/shirts → "clothing/shirts"+clothing/shirts/t-shirts → "clothing/shirts/t-shirts"+```++When a parent category is renamed, all child permalinks update automatically.++## Slug History++When a slug changes (e.g., a product is renamed), Spree records the old slug in its history table (`friendly_id_slugs`).++Note: the Store API product and category endpoints look up the *current* slug only (`find_by!` on the slug/permalink column) and do not automatically resolve retired slugs — a request using an old slug returns `404`. To preserve SEO and avoid broken links, issue HTTP 301 redirects from old slugs to the current one in your storefront or application layer.++## Internationalization++Products and categories support localized slugs — a different slug per locale. The locale is resolved from the request's [`X-Spree-Locale` header](/api-reference/store-api/localization):++<CodeGroup>++```typescript Store SDK+// English+const product = await client.products.get('red-shoes')++// French — locale goes in the third (request options) argument,+// which sends the X-Spree-Locale header+const product = await client.products.get('chaussures-rouges', undefined, {+ locale: 'fr',+})+```++```typescript Admin SDK+// Admin SDK accepts prefixed IDs only — not slugs+const product = await adminClient.products.get('prod_86Rf07xd4z')+```++```bash cURL+# English+curl 'https://api.mystore.com/api/v3/store/products/red-shoes' \+ -H 'X-Spree-API-Key: pk_xxx'++# French+curl 'https://api.mystore.com/api/v3/store/products/chaussures-rouges' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Locale: fr'+```++</CodeGroup>++Slugs are unique within the same locale but can be duplicated across different locales.++## Reserved Words++Spree prevents certain words from being used as slugs to avoid route conflicts: `new`, `edit`, `index`, `login`, `logout`, `admin`, and others.++## Related Documentation++- [Products](/v5/developer/core-concepts/products) — Product catalog+- [Translations](/v5/developer/core-concepts/translations) — Multi-language content+- [Querying](/api-reference/store-api/querying) — API resource lookup+- [Store SDK Products](/v5/developer/sdk/store/products) — `client.products.get()` slug/ID lookupdiff --git a/docs/v5/developer/core-concepts/staff-roles.mdx b/docs/v5/developer/core-concepts/staff-roles.mdxnew file mode 100644index 0000000000..8c0e1b4de3--- /dev/null+++ b/docs/v5/developer/core-concepts/staff-roles.mdx@@ -0,0 +1,175 @@+---+title: Staff & Roles+description: Manage Spree admin users, roles, invitations, and permissions — create admins via the CLI, scope access per store, and customize role-based permissions.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/staff-roles"+---++## Overview++Admin users manage the store via the Admin Panel. They have roles that control what they can access.++```mermaid+erDiagram+ AdminUser ||--o{ RoleUser : "has many"+ RoleUser }o--|| Role : "belongs to"+ RoleUser }o--|| Store : "scoped to"+ AdminUser ||--o{ Invitation : "invites"++ AdminUser {+ string id+ string email+ }++ RoleUser {+ string role_id+ string resource_type+ string resource_id+ }++ Role {+ string name+ }++ Invitation {+ string email+ string status+ string token+ datetime expires_at+ }+```++## Roles++Admin users can have different roles that control their permissions:++| Role | Description |+|------|-------------|+| `admin` | Full access to all Admin Panel features |++<Info>+You can create custom roles with specific permissions. See the [Customize Permissions guide](/v5/developer/customization/permissions) for details.+</Info>++## Creating Admin Users++Use the Spree CLI to create admin users:++```bash+spree user create+```++The CLI will prompt you for the email and password. You can also pass them directly:++```bash+spree user create --email [email protected] --password secret123+```++The created user gets the `admin` role on the default store.++## Authentication & identity providers++Staff authenticate against the Admin API, which issues a short-lived JWT used for subsequent requests. How a staff member proves who they are is **pluggable** — Spree ships email/password out of the box, and you can plug in any external identity provider (Okta, Microsoft Entra ID, Google Workspace, a custom JWT issuer, SAML, etc.) without changing the rest of the API.++### How admin login works++A staff member logs in via the `POST /api/v3/admin/auth/login` endpoint (see [Admin API Authentication](/api-reference/admin-api/authentication)). The request's `provider` field selects a registered **authentication strategy**. When `provider` is omitted it defaults to `email`, the built-in email/password strategy (which you can also disable and restrict the admin to your preferred SSO provider).++```mermaid+flowchart TB+ A["POST /api/v3/admin/auth/login"] --> B{"provider field"}+ B -->|"omitted or email"| C["Built-in EmailPasswordStrategy"]+ B -->|"okta, saml, ..."| D["Your custom strategy"]+ C --> E["Strategy authenticates, returns the staff user"]+ D --> E+ E --> F["Spree issues a JWT (aud=admin_api) + HttpOnly refresh cookie"]+```++Whichever strategy authenticates the request, Spree issues the **same** credentials in return, so downstream code and the admin SPA never need to know which provider was used:++- a JWT access token (`aud: admin_api`), short-lived by design;+- a rotating refresh token, set as an `HttpOnly` cookie scoped to `/api/v3/admin/auth` (the admin flow keeps it out of the response body — see [Admin Auth & Cookie Refresh](/api-reference/admin-api/authentication)).++The same strategy registry exists on the customer side, so storefront sign-in is pluggable the same way — the only difference is the user class and that the Store API returns the refresh token in the body rather than a cookie.++### Registering a custom identity provider++Follow the [Custom API Authentication how-to](/v5/developer/how-to/custom-api-authentication) for details how to create a custom authentication strategy and register it with the admin API. Once registered, you can use it from the admin SPA or any API client by passing its name in the `provider` field of the login request.++## Inviting Admin Users++You can invite new admins through the Admin Panel or programmatically.++**Via Admin Panel:**++1. Navigate to **Settings → Users**+2. Click **Invite User**+3. Enter the email address and select a role+4. Click **Send Invitation**++**Programmatically:**++Using the [Admin SDK](/v5/developer/sdk/admin/quickstart), call `client.invitations.create`:++```typescript+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++const invitation = await client.invitations.create({+ email: '[email protected]',+ role_id: 'role_xxx',+})+```++Creating an invitation publishes `invitation.created`, which sends the email. Either way, the invitee receives an email with an invitation link. If they already have an account, they log in to accept. Otherwise, they create an account first.++```mermaid+flowchart TB+ A[Admin creates invitation] --> B[Invitation email sent]+ B --> C[Invitee clicks link]+ C --> D{Has account?}+ D -->|Yes| E[Log in]+ D -->|No| F[Create account]+ E --> G[Accept invitation]+ F --> G+ G --> H[Role assigned to store]+```++### Invitation Details++| Attribute | Description |+|-----------|-------------|+| `email` | Invitee's email address |+| `token` | Secure token for the invitation link |+| `status` | `pending` or `accepted` |+| `expires_at` | Expiration date (default: 2 weeks) |+| `resource` | The store being granted access to |+| `role` | The role to assign upon acceptance |++### Invitation Events++The invitation system publishes [events](/v5/developer/core-concepts/events) you can subscribe to:++| Event | Description |+|-------|-------------|+| `invitation.created` | Invitation was created (triggers email) |+| `invitation.accepted` | Invitation was accepted and role assigned |+| `invitation.resent` | Invitation was resent to the invitee |++## Permissions++Spree uses [CanCanCan](https://github.com/CanCanCommunity/cancancan) for authorization. Permissions apply to both customers (Store API access) and admins (Admin Panel access).++See the [Customize Permissions guide](/v5/developer/customization/permissions) for details on creating custom roles and permission sets.++## Related Documentation++- [Admin SDK](/v5/developer/sdk/admin/quickstart) — the TypeScript client for back-office automation+- [Custom API Authentication](/v5/developer/how-to/custom-api-authentication) — implement a custom identity-provider strategy (the full guide)+- [Admin API Authentication](/api-reference/admin-api/authentication) — keys, JWTs, scopes, and the refresh-cookie flow+- [Customers](/v5/developer/core-concepts/customers) — Customer accounts and authentication+- [Permissions](/v5/developer/customization/permissions) — Roles and authorization+- [Events](/v5/developer/core-concepts/events) — Subscribe to invitation eventsdiff --git a/docs/v6/developer/core-concepts/store-credits-gift-cards.mdx b/docs/v5/developer/core-concepts/store-credits-gift-cards.mdxsimilarity index 89%rename from docs/v6/developer/core-concepts/store-credits-gift-cards.mdxrename to docs/v5/developer/core-concepts/store-credits-gift-cards.mdxindex 3eee606c5b..b0dd97c354 100644--- a/docs/v6/developer/core-concepts/store-credits-gift-cards.mdx+++ b/docs/v5/developer/core-concepts/store-credits-gift-cards.mdx@@ -1,6 +1,7 @@---title: Store Credits & Gift Cardsdescription: How Spree models store credits and gift cards — stored value balances, redeemable codes, and checkout usage for refunds, loyalty, and gifting.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/store-credits-gift-cards"---import { Since } from '/snippets/since.mdx';@@ -179,7 +180,7 @@ erDiagramGiftCard {string code- string status+ string statedecimal amountdecimal amount_useddecimal amount_authorized@@ -204,26 +205,28 @@ erDiagram| `code` | Unique redemption code | `abc1234def` || `amount` | Total gift card value | `50.00` || `amount_used` | Amount already redeemed | `0.00` |-| `status` | Current status | `active` |+| `state` | Current state | `active` || `currency` | Currency code | `USD` || `expires_at` | Optional expiration date | `2025-12-31` |-### Gift Card Statuses+### Gift Card States-| Status | Description | How it gets there |-|-------|-------------|-------------------|-| `active` | Available for redemption | The status a card is created with |-| `partially_redeemed` | Some value has been redeemed | `Spree::GiftCards::Redeem`, when a balance remains |-| `redeemed` | Fully redeemed | `Spree::GiftCards::Redeem`, when nothing is left |-| `canceled` | Voided, and no longer spendable | `Spree::GiftCards::Cancel` |--Redemption does not need the caller to choose: `Spree::GiftCards::Redeem`-looks at what is left on the card and marks it partially or fully redeemed-accordingly. A card can be partially redeemed more than once, and each spend-publishes its own event.+```mermaid+stateDiagram-v2+ [*] --> active: Created+ active --> partially_redeemed: Partial redemption+ active --> redeemed: Full redemption+ active --> canceled: Admin cancels+ partially_redeemed --> redeemed: Remaining redeemed+ partially_redeemed --> partially_redeemed: Another partial redemption+```-Cancelling is refused once a card has been spent against, so cancellation can-never take back value a customer has already used.+| State | Description |+|-------|-------------|+| `active` | Available for redemption |+| `partially_redeemed` | Some value has been redeemed |+| `redeemed` | Fully redeemed |+| `canceled` | Canceled by admin |<Note>Gift cards can also be `expired` if `expires_at` date has passed and the card hasn't been fully redeemed.@@ -338,7 +341,7 @@ When a gift card is applied to an order:- The gift card is marked as redeemed (or partially redeemed)- No Store Credit is created for guest checkouts-Gift cards are applied via a dedicated `POST /api/v3/store/carts/:cart_id/gift_cards` endpoint (separate from the `discount_codes` endpoint used for promotion codes); the discount-codes endpoint does not handle gift cards. See the [cart & checkout SDK guide](/developer/sdk/store/cart-checkout) for the full cart flow these calls belong to.+Gift cards are applied via a dedicated `POST /api/v3/store/carts/:cart_id/gift_cards` endpoint (separate from the `discount_codes` endpoint used for promotion codes); the discount-codes endpoint does not handle gift cards. See the [cart & checkout SDK guide](/v5/developer/sdk/store/cart-checkout) for the full cart flow these calls belong to.<CodeGroup>@@ -414,9 +417,9 @@ When a registered customer has multiple store credits, they are applied in order## Related Documentation-- [Payments](/developer/core-concepts/payments) — Payment processing and methods-- [Orders](/v6/developer/core-concepts/orders) — Order management-- [Customers](/developer/core-concepts/customers) — Customer management-- [Events](/developer/core-concepts/events) — Event system and subscribers-- [Admin SDK Quickstart](/developer/sdk/admin/quickstart) — Set up and authenticate the Admin SDK+- [Payments](/v5/developer/core-concepts/payments) — Payment processing and methods+- [Orders](/v5/developer/core-concepts/orders) — Order management+- [Customers](/v5/developer/core-concepts/customers) — Customer management+- [Events](/v5/developer/core-concepts/events) — Event system and subscribers+- [Admin SDK Quickstart](/v5/developer/sdk/admin/quickstart) — Set up and authenticate the Admin SDK- [Monetary Amounts](/api-reference/store-api/monetary-amounts) — How the API represents `amount`, `amount_used`, and other money fieldsdiff --git a/docs/v5/developer/core-concepts/stores.mdx b/docs/v5/developer/core-concepts/stores.mdxnew file mode 100644index 0000000000..d500356633--- /dev/null+++ b/docs/v5/developer/core-concepts/stores.mdx@@ -0,0 +1,97 @@+---+title: Stores+description: Understand Spree Stores — the top-level tenant boundary that scopes products, orders, channels, markets, and branding, with the Admin API for store config.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/stores"+---++## Overview++The Store is the top-level tenant in Spree. Every resource — products, orders, channels, markets, taxonomies — belongs to exactly one store. A store owns its [channels](/v5/developer/core-concepts/channels) (online, POS, wholesale, …), its [markets](/v5/developer/core-concepts/markets) (region/currency/locale), and its [product catalog](/v5/developer/core-concepts/products).++## Store Attributes++| Attribute | Description |+|-----------|-------------|+| `name` | Store name, displayed in the browser title and throughout the site |+| `code` | Unique identifier for the store |+| `url` | Primary URL of the store |+| `meta_description` | SEO description |+| `meta_keywords` | SEO keywords |+| `seo_title` | Custom SEO title |+| `customer_support_email` | Email for customer support inquiries |+| `mail_from_address` | Sender address for transactional emails |+| `logo_url` | URL to the store's logo |+| `facebook`, `twitter`, `instagram` | Social media links |+| `storefront_access` | Store-wide default for anonymous [storefront access gating](/v5/developer/core-concepts/channels#storefront-access-gating) (`public`, `prices_hidden`, `login_required`). Each channel can override it |+| `guest_checkout` | Store-wide default for whether orders can be placed without an account. Each channel can override it |++## Fetching Store Information++Store configuration is exposed through the Admin API. Use the store endpoint to read the current store's settings — name, URL, branding, and email addresses:++<CodeGroup>++```typescript Admin SDK+const store = await adminClient.store.get()+// {+// name: "My Store",+// url: "https://mystore.com",+// logo_url: "https://cdn.mystore.com/logo.png",+// mailer_logo_url: "https://cdn.mystore.com/mailer-logo.png",+// customer_support_email: "[email protected]",+// ...+// }+```++```bash cURL+curl 'https://api.mystore.com/api/v3/admin/store' \+ -H 'X-Spree-API-Key: sk_xxx'+```++</CodeGroup>++This is an admin endpoint, so it requires a secret API key (`sk_xxx`) or a Bearer JWT — a publishable key cannot reach it.++## Channels vs. Markets++Two different ways to split a store, often confused:++- **[Sales Channels](/v5/developer/core-concepts/channels)** segment **selling surfaces** — Online Store, POS, Wholesale, marketplace integrations. They control product visibility, order attribution, and per-channel routing rules.+- **[Markets](/v5/developer/core-concepts/markets)** segment **geography and currency** — North America (USD/en), Europe (EUR/de), UK (GBP/en). They control which currency, locale, and tax rules apply to a given customer.++A single Online Store channel can serve multiple markets (one storefront → many regions). Conversely, POS and Online channels can share the same market (same currency/locale, different selling surfaces).++### Storefront access defaults++The store sets the fallback for **storefront access gating** — whether anonymous visitors may browse, see prices, or must sign in first — via `storefront_access` (`public`, `prices_hidden`, `login_required`) and the companion `guest_checkout` control. Each channel inherits these unless it sets its own value, so you can gate a whole store or just one channel (e.g. a `login_required` wholesale channel on an otherwise `public` store). The full behavior of each mode and how the Store API enforces it lives in [Channels → Storefront Access Gating](/v5/developer/core-concepts/channels#storefront-access-gating).++## Store Resources++Each store owns its own resources. Products, orders, channels, markets, and taxonomies in one store are independent from another.++| Resource | Relationship |+|----------|-------------|+| [**Channels**](/v5/developer/core-concepts/channels) | A store has many channels (Online Store, POS, Wholesale, …). One is the default. |+| [**Markets**](/v5/developer/core-concepts/markets) | A store has many markets, each defining a geographic region with its own currency and locale |+| [**Orders**](/v5/developer/core-concepts/orders) | An order belongs to one store and one channel |+| [**Products**](/v5/developer/core-concepts/products) | A product belongs to one store. Its visibility across channels is controlled by [publications](/v5/developer/core-concepts/channels#publishing-products-on-channels). |+| [**Categories**](/v5/developer/core-concepts/products#categories) | A category belongs to one store |+| [**Payment Methods**](/v5/developer/core-concepts/payments) | A payment method belongs to one store |+| [**Shipping Methods**](/v5/developer/core-concepts/shipments) | A shipping method belongs to one store |+| [**Promotions**](/v5/developer/core-concepts/promotions) | A promotion belongs to one store |++## Running Multiple Storefronts++If you need one Spree backend to serve **multiple distinct merchant brands** — different domains, different catalogs — there are two patterns:++- **Multiple channels under one store** (recommended for most cases) — model each storefront as a Sales Channel. Products are scoped per-channel via publications, orders carry the channel that originated them, and routing/pricing can differ per channel. This is the supported pattern in core Spree 5.5+.+- **Multiple isolated stores (tenants) in one app** — full data isolation, only recommended if you're building a SaaS platform or a multi-tenant application. Each store can have different staff members, payment methods, shipping methods, and branding. This is supported by the [Spree Multi Tenant](/v5/developer/multi-tenant/quickstart) extension, which is a separate gem from core Spree.++## Related Documentation++- [Channels](/v5/developer/core-concepts/channels) — Selling surfaces (Online, POS, Wholesale, …)+- [Markets](/v5/developer/core-concepts/markets) — Multi-region commerce within a store+- [Products](/v5/developer/core-concepts/products) — Product catalog+- [Orders](/v5/developer/core-concepts/orders) — Order management and checkout+- [Wholesale Portal](/v5/developer/storefront/nextjs/wholesale) — A gated B2B storefront surface built on channel access gating+- [Admin SDK](/v5/developer/sdk/admin/quickstart) — TypeScript client for the Admin API used to read and update store configurationdiff --git a/docs/v5/developer/core-concepts/taxes.mdx b/docs/v5/developer/core-concepts/taxes.mdxnew file mode 100644index 0000000000..dc36b1c424--- /dev/null+++ b/docs/v5/developer/core-concepts/taxes.mdx@@ -0,0 +1,170 @@+---+title: Taxes+description: Tax categories, tax rates, zones, and how Spree calculates taxes at checkout+canonical: "https://spreecommerce.org/docs/developer/core-concepts/taxes"+---++## Overview++Spree uses Tax Categories and Tax Rates to calculate taxes for orders. Products are assigned to tax categories, and tax rates define the percentage charged within specific geographic [Zones](/v5/developer/core-concepts/addresses#zones).++```mermaid+erDiagram+ TaxCategory ||--o{ TaxRate : "has many"+ TaxCategory ||--o{ Product : "has many"+ TaxRate }o--|| Zone : "applies in"+ TaxRate ||--o{ Adjustment : "creates"+ Zone ||--o{ ZoneMember : "has many"++ TaxCategory {+ string name+ boolean is_default+ string tax_code+ }++ TaxRate {+ string name+ decimal amount+ boolean included_in_price+ }++ Zone {+ string name+ string kind+ }+```++**Key relationships:**+- **Tax Category** groups products for tax purposes (e.g., "Clothing", "Food", "Digital")+- **Tax Rate** defines the percentage and rules for a Tax Category within a [Zone](/v5/developer/core-concepts/addresses#zones)+- **Zone** defines geographic regions (countries or states) where taxes apply+- **[Adjustments](/v5/developer/core-concepts/adjustments)** are created on orders/line items to apply taxes++## Tax Categories++Tax categories group products by how they're taxed. Common examples:++- **Clothing** — standard tax rate+- **Food** — reduced or exempt rate+- **Digital** — different rules per jurisdiction++Each product is assigned a tax category. One category can be set as the default for products that don't have an explicit assignment.++| Attribute | Description | Example |+|-----------|-------------|---------|+| `name` | Category name | `Clothing` |+| `is_default` | Whether this is the default category | `true` |+| `tax_code` | Code from your tax provider (e.g., Stripe, Avalara) | `1257L` |++Manage tax categories via the [Admin API](/api-reference/admin-api/introduction), using the [Admin SDK resource clients](/v5/developer/sdk/admin/resources):++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++const clothing = await client.taxCategories.create({+ name: 'Clothing',+ tax_code: '1257L',+ is_default: true,+})++await client.taxCategories.update('taxcat_xxx', { is_default: false })+await client.taxCategories.delete('taxcat_xxx')+```++```bash CLI+spree api post /tax_categories -d '{"name": "Clothing", "tax_code": "1257L", "is_default": true}'+spree api get /tax_categories+```++</CodeGroup>++## Tax Rates++Tax rates define the percentage charged for a specific tax category within a geographic zone.++| Attribute | Description | Example |+|-----------|-------------|---------|+| `name` | Rate name | `California Sales Tax` |+| `amount` | Tax percentage as a decimal | `0.08` (8%) |+| `included_in_price` | Whether tax is included in the displayed price | `false` |+| `zone` | Geographic region where this rate applies | `US` |+| `tax_category` | Products this rate applies to | `Clothing` |++## Tax Types++### Sales Tax (tax-exclusive)++Common in the United States. The displayed price does **not** include tax — tax is added at checkout based on the shipping address.++**Example:** A $17.99 item with 5% sales tax:+- Displayed price: **$17.99**+- Tax at checkout: **$0.90**+- Order total: **$18.89**++### Value Added Tax / VAT (tax-inclusive)++Common in Europe and many other countries. The displayed price **already includes** tax. When shipping outside the tax zone, the tax is removed from the price.++**Example:** A £17.99 item with 5% VAT included:+- Displayed price: **£17.99** (includes £0.86 VAT)+- If shipped outside VAT zone: price reduces to **£17.13**++<Info>+The `tax_inclusive` setting on [Markets](/v5/developer/core-concepts/markets) controls whether prices are displayed with or without tax for each geographic region.+</Info>++## Default Tax Zone++Spree uses a default tax zone to estimate taxes before the customer enters a shipping address. This is important for stores with tax-inclusive pricing (VAT) — it determines which tax rate is assumed in the displayed price.++If the customer's shipping address is outside the default tax zone, the assumed tax is removed and the correct rate for their zone is applied.++## Tax Calculation at Checkout++During checkout, taxes are calculated based on the shipping address:++1. The customer's shipping address determines their [Zone](/v5/developer/core-concepts/addresses#zones)+2. Spree finds matching tax rates for that zone and the product's tax category+3. Tax [Adjustments](/v5/developer/core-concepts/adjustments) are created on line items+4. The order total is updated++<Note>+For complex tax requirements (interstate US sales, international VAT), consider using automated tax calculation. The [Stripe Tax integration](/integrations/payments/stripe) handles this automatically.+</Note>++## Managing Taxes++Tax categories and rates are managed in the Admin Panel under **Settings → Taxes**, or via the Admin API.++### Common Configurations++**US store with state-level sales tax:**+- Create zones for each taxable state+- Create tax rates per zone (e.g., 8.25% for California, 6.25% for Texas)+- Set `included_in_price: false`++**EU store with VAT:**+- Create a zone for EU countries+- Create tax rates per country (e.g., 19% Germany, 20% France)+- Set `included_in_price: true`+- Set the EU zone as the default tax zone++**Digital products in the EU:**+- Create a "Digital" tax category+- Add tax rates for each EU country using the customer's country VAT rate+- Physical products use the seller's country VAT rate++## Related Documentation++- [Markets](/v5/developer/core-concepts/markets) — Tax-inclusive pricing per market+- [Addresses](/v5/developer/core-concepts/addresses) — Zones and address-based taxation+- [Adjustments](/v5/developer/core-concepts/adjustments) — Tax adjustments+- [Orders](/v5/developer/core-concepts/orders) — How taxes affect order totals+- [Avalara integration](/integrations/tax/avalara) — Automated tax calculation for complex jurisdictionsdiff --git a/docs/v5/developer/core-concepts/translations.mdx b/docs/v5/developer/core-concepts/translations.mdxnew file mode 100644index 0000000000..0cc0746108--- /dev/null+++ b/docs/v5/developer/core-concepts/translations.mdx@@ -0,0 +1,141 @@+---+title: Translations+description: Translate Spree products, taxons, and other store content into multiple languages using Mobility-backed translations and locale-aware APIs.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/translations"+---++## Overview++Spree supports two types of translations:++1. **Resource Translations** — translatable content fields on models like Products, Taxons, and Stores (e.g., product name, description, slug)+2. **UI Translations** — interface strings used in the admin panel (e.g., button labels, flash messages)++For configuring which locales and currencies are available in your store, see [Markets](/v5/developer/core-concepts/markets). Markets control locale and currency assignment per geographic region.++## Resource Translations++Resources with user-facing content fields have built-in support for translations. Each translatable resource has a corresponding translations table in the database — for example, product translations are stored in `spree_product_translations`.++```mermaid+erDiagram+ Product ||--o{ ProductTranslation : "has many"+ Taxon ||--o{ TaxonTranslation : "has many"+ Store ||--o{ StoreTranslation : "has many"++ Product {+ string id PK+ string status+ }++ ProductTranslation {+ string id PK+ string product_id FK+ string locale+ string name+ text description+ string slug+ string meta_title+ string meta_description+ }++ TaxonTranslation {+ string id PK+ string taxon_id FK+ string locale+ string name+ text description+ string permalink+ }+```++### Translatable Fields++| Resource | Translatable Fields |+| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Product | `name`, `description`, `slug`, `meta_description`, `meta_title` |+| Taxon | `name`, `description`, `permalink` |+| Taxonomy | `name` |+| Option Type | `presentation` |+| Option Value | `presentation` |+| Property | `presentation` |+| Product Property | `value` |+| Store | `name`, `meta_description`, `meta_keywords`, `seo_title`, `customer_support_email`, `address`, `contact_phone` |++### Store API++To retrieve translated content, pass the locale via the [`X-Spree-Locale` header](/api-reference/store-api/localization) or the SDK `locale` option:++<CodeGroup>++```typescript Store SDK+// Fetch product in French+const product = await client.products.get('spree-tote', {}, {+ locale: 'fr',+})++product.name // "Sac Spree"+product.description // "Un sac fourre-tout élégant..."+product.slug // "sac-spree"++// List categories in German+const { data: categories } = await client.categories.list({}, {+ locale: 'de',+})+```++```typescript Admin SDK+// Pass the locale as a request option to get translated content.+// The Admin API resolves by prefixed ID only — slugs are not accepted.+const product = await adminClient.products.get('prod_86Rf07xd4z', {}, { locale: 'fr' })++const { data: categories } = await adminClient.categories.list({}, { locale: 'de' })+```++```bash cURL+# Fetch product in French+curl 'https://api.mystore.com/api/v3/store/products/spree-tote' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Locale: fr'+```++</CodeGroup>++Slugs are also localized — a product can have different slugs per locale. See [Slugs](/v5/developer/core-concepts/slugs#internationalization) for details.++### Managing Translations++Translations are managed in the Admin Panel. When editing a product, taxon, or other translatable resource, switch the locale selector to enter content in each language.++Translations can also be [managed via the Admin API](/v5/developer/sdk/admin/quickstart).++## UI Translations++Spree stores UI translation strings in a separate project: [Spree I18n](https://github.com/spree-contrib/spree_i18n). This is a community-maintained project with locale files for 43+ languages.++To install UI translations:++<CodeGroup>++```bash Spree CLI (Docker)+spree bundle add spree_i18n+```++```bash Without Spree CLI+bundle add spree_i18n+```++</CodeGroup>++Once installed, all translation files are available automatically — no need to copy any files.++<Info>+The full list of supported locales is available in the [Spree I18n GitHub repository](https://github.com/spree-contrib/spree_i18n/tree/main/config/locales).+</Info>++## Related Documentation++- [Markets](/v5/developer/core-concepts/markets) — Locale and currency configuration per geographic region+- [Localization](/api-reference/store-api/localization) — Locale, currency, and country headers in API requests+- [Slugs](/v5/developer/core-concepts/slugs) — Localized slugs and URL identifiers+- [Products](/v5/developer/core-concepts/products) — Product translationsdiff --git a/docs/developer/core-concepts/users.mdx b/docs/v5/developer/core-concepts/users.mdxsimilarity index 85%rename from docs/developer/core-concepts/users.mdxrename to docs/v5/developer/core-concepts/users.mdxindex 05a6ec8d24..6dc5c2abac 100644--- a/docs/developer/core-concepts/users.mdx+++ b/docs/v5/developer/core-concepts/users.mdx@@ -1,6 +1,7 @@---title: Usersdescription: How Spree models customer and admin users — Devise authentication, account data, roles, abilities, and access permissions across stores.+canonical: "https://spreecommerce.org/docs/v5/developer/core-concepts/users"---## Overview@@ -16,7 +17,7 @@ Spree has two separate user types:| Admins | `Spree.admin_user_class` | `Spree::AdminUser` |<Info>-You can use your own user classes. See the [Customize Authentication guide](/developer/customization/authentication) for details.+You can use your own user classes. See the [Customize Authentication guide](/v5/developer/customization/authentication) for details.</Info>## Customers@@ -111,7 +112,7 @@ curl -X POST 'https://api.mystore.com/api/v3/store/auth/login' \</CodeGroup>-The response includes a [JWT token](/api-reference/store-api/authentication) and a `user` object. Pass the token in subsequent requests via the `Authorization: Bearer <token>` header. See the [account SDK guide](/developer/sdk/store/account) for the full `auth.login`, refresh, and profile flows.+The response includes a [JWT token](/api-reference/store-api/authentication) and a `user` object. Pass the token in subsequent requests via the `Authorization: Bearer <token>` header. See the [account SDK guide](/v5/developer/sdk/store/account) for the full `auth.login`, refresh, and profile flows.### Token Refresh@@ -178,8 +179,8 @@ Authenticated customers have access to these resources:| Resource | Description ||----------|-------------|-| [**Addresses**](/developer/core-concepts/addresses#customer-address-book) | Billing and shipping addresses with default selection |-| [**Orders**](/developer/core-concepts/orders#order-history) | Past order history |+| [**Addresses**](/v5/developer/core-concepts/addresses#customer-address-book) | Billing and shipping addresses with default selection |+| [**Orders**](/v5/developer/core-concepts/orders#order-history) | Past order history || **Credit Cards** | Saved credit cards for checkout || **Payment Sources** | Other saved payment methods (PayPal, Klarna, etc.) || **Store Credits** | Balance assigned by the store, usable at checkout |@@ -188,7 +189,7 @@ Authenticated customers have access to these resources:### Guest Checkout-Customers don't need to register to purchase. Guest checkout uses an order token (`X-Spree-Token`) to identify the cart. See [Orders — Cart](/developer/core-concepts/orders#cart) for details.+Customers don't need to register to purchase. Guest checkout uses an order token (`X-Spree-Token`) to identify the cart. See [Orders — Cart](/v5/developer/core-concepts/orders#cart) for details.## Admin Users@@ -233,7 +234,7 @@ Admin users can have different roles that control their permissions:| `admin` | Full access to all Admin Panel features |<Info>-You can create custom roles with specific permissions. See the [Customize Permissions guide](/developer/customization/permissions) for details.+You can create custom roles with specific permissions. See the [Customize Permissions guide](/v5/developer/customization/permissions) for details.</Info>### Creating Admin Users@@ -290,7 +291,7 @@ flowchart TB#### Invitation Events-The invitation system publishes [events](/developer/core-concepts/events) you can subscribe to:+The invitation system publishes [events](/v5/developer/core-concepts/events) you can subscribe to:| Event | Description ||-------|-------------|@@ -302,14 +303,14 @@ The invitation system publishes [events](/developer/core-concepts/events) you caSpree uses [CanCanCan](https://github.com/CanCanCommunity/cancancan) for authorization. Permissions apply to both customers (Store API access) and admins (Admin Panel access).-See the [Customize Permissions guide](/developer/customization/permissions) for details on creating custom roles and permission sets.+See the [Customize Permissions guide](/v5/developer/customization/permissions) for details on creating custom roles and permission sets.## Related Documentation-- [Addresses](/developer/core-concepts/addresses) — Customer address management-- [Orders](/developer/core-concepts/orders) — Order history and checkout-- [Authentication](/developer/customization/authentication) — Custom authentication setup-- [Permissions](/developer/customization/permissions) — Roles and authorization-- [Events](/developer/core-concepts/events) — Subscribe to user and invitation events+- [Addresses](/v5/developer/core-concepts/addresses) — Customer address management+- [Orders](/v5/developer/core-concepts/orders) — Order history and checkout+- [Authentication](/v5/developer/customization/authentication) — Custom authentication setup+- [Permissions](/v5/developer/customization/permissions) — Roles and authorization+- [Events](/v5/developer/core-concepts/events) — Subscribe to user and invitation events- [Store API Authentication](/api-reference/store-api/authentication) — Customer JWT auth flow- [Admin API Authentication](/api-reference/admin-api/authentication) — Staff JWT + scopes auth flowdiff --git a/docs/v5/developer/core-concepts/webhooks.mdx b/docs/v5/developer/core-concepts/webhooks.mdxnew file mode 100644index 0000000000..b4957903e2--- /dev/null+++ b/docs/v5/developer/core-concepts/webhooks.mdx@@ -0,0 +1,451 @@+---+title: Webhooks+description: Send real-time HTTP notifications to external services when events occur in your store.+canonical: "https://spreecommerce.org/docs/developer/core-concepts/webhooks"+---++import { Since } from '/snippets/since.mdx';++<Since version="5.3" />++## Overview++Webhooks allow your Spree store to send real-time HTTP POST notifications to external services when events occur. When an order is completed, a product is updated, or inventory changes, Spree can automatically notify your CRM, fulfillment service, analytics platform, or any other system.++Webhooks are built on top of Spree's [event system](/v5/developer/core-concepts/events), providing:++- **Multi-store support** - Each store has its own webhook endpoints+- **Event filtering** - Subscribe to specific events or patterns with wildcards+- **Secure delivery** - HMAC-SHA256 signatures for payload verification+- **Automatic retries** - Failed deliveries retry with exponential backoff+- **Full audit trail** - Track every delivery attempt with response codes and timing++## How Webhooks Work++```mermaid+flowchart LR+ subgraph Spree Store+ A[Event Published] --> B[WebhookEventSubscriber]+ B --> C{Find Matching<br/>Endpoints}+ C --> D[Create WebhookDelivery]+ D --> E[Queue DeliveryJob]+ end++ subgraph Delivery+ E --> F[Build JSON Payload]+ F --> G[Sign with HMAC-SHA256]+ G --> H[HTTP POST]+ end++ subgraph External Service+ H --> I{Response}+ I -->|2xx| J[Success]+ I -->|Error| K[Retry with Backoff]+ K -->|Max Retries| L[Mark Failed]+ K -->|Retry| H+ end+```++1. An event is published (e.g., `order.completed`)+2. The `WebhookEventSubscriber` receives all events+3. It finds active webhook endpoints subscribed to that event+4. For each endpoint, it creates a `WebhookDelivery` record and queues a job+5. The job sends an HTTP POST request with the event payload and HMAC signature++## Creating Webhook Endpoints++### Via Admin Panel++Navigate to **Settings → Developers → Webhooks** in the admin panel to create and manage webhook endpoints.++### Via the Admin API++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++const endpoint = await client.webhookEndpoints.create({+ url: 'https://example.com/webhooks/spree',+ subscriptions: ['order.*', 'product.created'],+ active: true,+})++// secret_key is auto-generated and returned ONLY on create —+// store it now for HMAC signature verification.+endpoint.secret_key // => "a1b2c3d4e5f6..." (64-character hex string)+```++```bash CLI+spree api post /webhook_endpoints -d '{+ "url": "https://example.com/webhooks/spree",+ "subscriptions": ["order.*", "product.created"],+ "active": true+}'+```++</CodeGroup>++<Warning>+The `secret_key` is returned **only once**, in the create response. Save it immediately — it can't be retrieved later and is required to verify webhook signatures.+</Warning>++### Endpoint Attributes++| Attribute | Type | Description |+|-----------|------|-------------|+| `url` | String | The HTTPS endpoint URL to receive webhooks |+| `active` | Boolean | Enable/disable delivery to this endpoint |+| `subscriptions` | Array | Event patterns to subscribe to |+| `secret_key` | String | Auto-generated key for HMAC signature verification |++Endpoints always belong to the current store — the association is set automatically from the request scope, so you never pass it when creating or updating an endpoint.++## Event Subscriptions++The `subscriptions` attribute controls which events trigger webhooks to this endpoint. Set it when creating the endpoint, or change it later:++<CodeGroup>++```typescript Admin SDK+await client.webhookEndpoints.update('whe_xxx', {+ subscriptions: ['order.completed', 'order.canceled'],+})+```++```bash CLI+spree api patch /webhook_endpoints/whe_xxx \+ -d '{"subscriptions": ["order.completed", "order.canceled"]}'+```++</CodeGroup>++The `subscriptions` array accepts exact event names and wildcard patterns:++| `subscriptions` value | Receives |+|---|---|+| `['order.completed', 'order.canceled']` | Only those two events |+| `['order.*']` | All order events |+| `['*.created']` | All creation events |+| `['order.*', 'payment.*', 'shipment.shipped']` | Multiple patterns |+| `[]` or `['*']` | All events |++## Webhook Payload++Each webhook delivery sends a JSON payload with the following structure. The `data` object uses the same [Store API V3 serializers](/api-reference/introduction) as the REST API, so webhook payloads and API responses share the same schema:++```json+{+ "id": "550e8400-e29b-41d4-a716-446655440000",+ "name": "order.completed",+ "created_at": "2025-01-15T10:30:00Z",+ "data": {+ "id": "or_m3Rp9wXz",+ "number": "R123456789",+ "fulfillment_status": "shipped",+ "payment_status": "paid",+ "total": "99.99",+ "display_total": "$99.99",+ "total_quantity": 3,+ "currency": "USD",+ "items": [ ... ],+ "fulfillments": [ ... ],+ "payments": [ ... ]+ },+ "metadata": {+ "spree_version": "5.1.0"+ }+}+```++| Field | Description |+|-------|-------------|+| `id` | Unique UUID for this event |+| `name` | Event name (e.g., `order.completed`) |+| `created_at` | ISO8601 timestamp when event occurred |+| `data` | Serialized resource data (V3 API format with [prefixed IDs](/api-reference/introduction)) |+| `metadata` | Additional context including Spree version |++For complete payload schemas for each event type, see [Webhook Events & Payloads](/api-reference/webhooks-events).++## HTTP Request Details++### Headers++Each webhook request includes these headers:++| Header | Description |+|--------|-------------|+| `Content-Type` | `application/json` |+| `User-Agent` | `Spree-Webhooks/1.0` |+| `X-Spree-Webhook-Event` | Event name (e.g., `order.completed`) |+| `X-Spree-Webhook-Signature` | HMAC-SHA256 signature for verification |+| `X-Spree-Webhook-Timestamp` | Unix timestamp (seconds) generated at send time; included in the HMAC-SHA256 signed string as `{timestamp}.{payload}` and required to verify `X-Spree-Webhook-Signature` |++### Verifying Webhook Signatures++To ensure webhooks are genuinely from your Spree store, verify the signature.++#### Next.js++The [Spree Storefront](https://github.com/spree/storefront) includes a ready-made webhook route handler with signature verification and event routing. See the [storefront email docs](/v5/developer/storefront/nextjs/customization#transactional-emails) for details.++#### Any JavaScript/TypeScript framework++Use `@spree/sdk/webhooks` for framework-agnostic verification:++```typescript+import { verifyWebhookSignature } from '@spree/sdk/webhooks'+import type { WebhookEvent } from '@spree/sdk/webhooks'+import type { Order } from '@spree/sdk'++// Hono, Cloudflare Workers, or any Web Fetch API-based framework+app.post('/webhooks/spree', async (req, res) => {+ const body = await req.text()+ const signature = req.headers['x-spree-webhook-signature']+ const timestamp = req.headers['x-spree-webhook-timestamp']++ if (!verifyWebhookSignature(body, signature, timestamp, process.env.SPREE_WEBHOOK_SECRET!)) {+ return res.status(401).json({ error: 'Invalid signature' })+ }++ const event: WebhookEvent<Order> = JSON.parse(body)+ // handle event...+ res.json({ received: true })+})+```++#### Ruby++```ruby+class WebhooksController < ApplicationController+ skip_before_action :verify_authenticity_token++ def receive+ unless verify_signature+ head :unauthorized+ return+ end++ event = JSON.parse(request.body.read)++ case event['name']+ when 'order.completed'+ handle_order_completed(event['data'])+ when 'product.updated'+ handle_product_updated(event['data'])+ end++ head :ok+ end++ private++ def verify_signature+ payload = request.body.read+ request.body.rewind++ signature = request.headers['X-Spree-Webhook-Signature']+ timestamp = request.headers['X-Spree-Webhook-Timestamp']+ expected = OpenSSL::HMAC.hexdigest('SHA256', ENV['SPREE_WEBHOOK_SECRET'], "#{timestamp}.#{payload}")++ ActiveSupport::SecurityUtils.secure_compare(signature.to_s, expected)+ end+end+```++## Delivery Status & Retries++### Automatic Retries++Failed webhook deliveries automatically retry up to 5 times with exponential backoff. This handles temporary network issues and endpoint downtime.++### Checking Delivery Status++Inspect an endpoint's delivery log, and re-send a failed delivery, via the Admin API:++<CodeGroup>++```typescript Admin SDK+// Recent deliveries for an endpoint+const { data: deliveries } = await client.webhookEndpoints.deliveries.list('whe_xxx')++// Re-send a specific delivery+await client.webhookEndpoints.deliveries.redeliver('whe_xxx', 'whd_xxx')+```++```bash CLI+spree api get /webhook_endpoints/whe_xxx/deliveries -q event_name_eq=order.completed+spree api post /webhook_endpoints/whe_xxx/deliveries/whd_xxx/redeliver+```++</CodeGroup>++### Delivery Attributes++| Attribute | Description |+|-----------|-------------|+| `event_name` | Name of the event delivered |+| `payload` | Complete webhook payload sent |+| `response_code` | HTTP status code (nil if pending) |+| `success` | Boolean indicating 2xx response |+| `execution_time` | Delivery time in milliseconds |+| `error_type` | `'timeout'`, `'connection_error'`, or nil |+| `request_errors` | Error message details |+| `response_body` | Response from endpoint (truncated) |+| `delivered_at` | Timestamp of delivery attempt |++## Configuration++### Enabling/Disabling Webhooks++Webhooks are enabled by default. To disable globally:++```ruby+# config/initializers/spree.rb+Spree::Api::Config.webhooks_enabled = false+```++### SSL Verification++SSL verification is enabled by default in production. In development, it's disabled to allow testing with self-signed certificates:++```ruby+# config/initializers/spree.rb+Spree::Api::Config.webhooks_verify_ssl = true # Force SSL verification+Spree::Api::Config.webhooks_verify_ssl = false # Disable (not recommended for production)+```++## Available Events++Webhooks can subscribe to any event in Spree's event system. See [Events](/v5/developer/core-concepts/events#available-events) for a complete list.++Common webhook events include:++| Event | Description |+|-------|-------------|+| `order.completed` | Order checkout finished |+| `order.canceled` | Order was canceled |+| `order.paid` | Order is fully paid |+| `shipment.shipped` | Shipment was shipped |+| `payment.paid` | Payment was completed |+| `product.created` | New product created |+| `product.updated` | Product was modified |+| `user.created` | New customer/user registered (the admin user class emits `admin.created`) |++## Testing Webhooks++### In Development++Use tools like [ngrok](https://ngrok.com) or [webhook.site](https://webhook.site) to test webhooks locally. Create a test endpoint pointed at the tunnel:++<CodeGroup>++```typescript Admin SDK+const endpoint = await client.webhookEndpoints.create({+ url: 'https://your-ngrok-url.ngrok.io/webhooks',+ subscriptions: ['order.*'],+ active: true,+})++// Fire a synthetic delivery to confirm it's reachable+await client.webhookEndpoints.sendTest(endpoint.id)+```++```bash CLI+spree api post /webhook_endpoints -d '{+ "url": "https://your-ngrok-url.ngrok.io/webhooks",+ "subscriptions": ["order.*"],+ "active": true+}'+spree api post /webhook_endpoints/whe_xxx/send_test+```++</CodeGroup>++`send_test` delivers a synthetic `webhook.test` event so you can verify the endpoint is reachable and your signature-verification code works, without having to trigger a real order.++### In Tests++```ruby+RSpec.describe 'Webhook delivery' do+ let(:store) { create(:store) }+ let(:endpoint) { create(:webhook_endpoint, store: store, subscriptions: ['order.completed']) }+ let(:order) { create(:completed_order_with_totals, store: store) }++ it 'delivers webhook when order completes' do+ stub_request(:post, endpoint.url).to_return(status: 200)++ expect {+ order.publish_event('order.completed')+ }.to have_enqueued_job(Spree::WebhookDeliveryJob)+ end+end+```++## Best Practices++<CardGroup cols={2}>+ <Card title="Respond quickly" icon="bolt">+ Return a 2xx response as fast as possible. Process webhook data asynchronously in a background job.+ </Card>++ <Card title="Verify signatures" icon="shield">+ Always verify the `X-Spree-Webhook-Signature` header to ensure the webhook is authentic.+ </Card>++ <Card title="Handle duplicates" icon="copy">+ Use the event `id` to detect and handle duplicate deliveries. Webhooks may be retried.+ </Card>++ <Card title="Subscribe selectively" icon="filter">+ Only subscribe to events you need. Use specific patterns rather than `*` when possible.+ </Card>+</CardGroup>++## Troubleshooting++### Webhooks Not Delivering++1. Check that webhooks are enabled: `Spree::Api::Config.webhooks_enabled`+2. Verify the endpoint is active: `endpoint.active?`+3. Confirm the endpoint subscribes to the event: `endpoint.subscribed_to?('order.completed')`+4. Check the event has a `store_id` matching the endpoint's store++### Signature Verification Failing++1. Ensure you're using the raw request body (not parsed JSON)+2. Verify you're using the correct `secret_key` for this endpoint+3. Check that no middleware is modifying the request body++### Deliveries Failing++Check the delivery records for details — each carries `error_type`, `request_errors`, `response_code`, and `response_body`. Filter the log with [Ransack predicates](/api-reference/admin-api/querying) such as `success_eq=false` or `event_name_eq`:++<CodeGroup>++```typescript Admin SDK+const { data: deliveries } = await client.webhookEndpoints.deliveries.list('whe_xxx', {+ success_eq: false,+})+const failed = deliveries[0]+// failed.error_type, failed.request_errors, failed.response_code, failed.response_body+```++```bash CLI+spree api get /webhook_endpoints/whe_xxx/deliveries -q success_eq=false+```++</CodeGroup>++## Related Documentation++- [Events](/v5/developer/core-concepts/events) - Understanding Spree's event system+- [Admin SDK](/v5/developer/sdk/admin/quickstart) - Setting up the `@spree/admin-sdk` client used in the management examples above+- [Customization Quickstart](/v5/developer/customization/quickstart) - Overview of all customization options+- [Dependencies](/v5/developer/customization/dependencies) - Customizing Spree servicesdiff --git a/docs/v5/developer/create-spree-app/quickstart.mdx b/docs/v5/developer/create-spree-app/quickstart.mdxnew file mode 100644index 0000000000..46cc67cc97--- /dev/null+++ b/docs/v5/developer/create-spree-app/quickstart.mdx@@ -0,0 +1,192 @@+---+title: "create-spree-app"+sidebarTitle: Overview+description: "Scaffold a new Spree Commerce project with a single command — bootstraps a full Rails backend, Docker dev stack, and the @spree/cli for customization."+canonical: "https://spreecommerce.org/docs/developer/create-spree-app/quickstart"+---++## Quick Start++```bash+npx create-spree-app@latest my-store+```++The CLI walks you through an interactive setup:++1. Include **Next.js Storefront** (default: yes)+2. Optionally load **sample data** (products, categories, images)+3. Optionally **start Docker services** immediately++Once complete, your store is running at [http://localhost:3000](http://localhost:3000) — setup pulls the latest Spree image, seeds the database, and configures API keys, then prints a summary with your admin credentials and keys. If you skipped starting services, the first `pnpm dev` completes setup automatically.++The **React Dashboard** (Developer Preview of the next-generation admin) is available with the `--react-dashboard` flag, or later via `spree add dashboard`.++## Prerequisites++- [Node.js](https://nodejs.org/) 20 or later+- [Docker](https://docs.docker.com/get-docker/) (for running the Spree backend, PostgreSQL, and Meilisearch)++## CLI Flags++All prompts can be skipped with flags for non-interactive (CI/CD) usage:++```bash+npx create-spree-app@latest my-store --no-storefront --no-sample-data --no-start+```++| Flag | Description |+|------|-------------|+| `--react-dashboard` | Include the React Dashboard (Developer Preview — also available later via `spree add dashboard`) |+| `--no-storefront` | Skip Next.js storefront setup |+| `--no-sample-data` | Skip loading sample products and categories |+| `--no-start` | Don't start Docker services after scaffolding |+| `--port <number>` | Port for the Spree backend (default: `3000`) |+| `--use-npm` | Use npm as package manager |+| `--use-yarn` | Use yarn as package manager |+| `--use-pnpm` | Use pnpm as package manager |++<Tip>+ The package manager is auto-detected from how you run the command. If you use `pnpm dlx create-spree-app`, pnpm will be used automatically.+</Tip>++<Tip>+ If the default port is already in use, the CLI will automatically find a free port and let you know.+</Tip>++## Generated Project Structure++```text+my-store/+├── docker-compose.yml # Spree backend (prebuilt image) + Postgres + Meilisearch+├── docker-compose.dev.yml # Alternative: build from local backend/+├── render.yaml # Render Blueprint — one Docker service built from this repo+├── .env # SECRET_KEY_BASE, SPREE_PORT, SPREE_VERSION_TAG, SPREE_SAMPLE_DATA+├── .dockerignore # Keeps the production build context to sources+├── .gitignore+├── package.json # Convenience scripts+├── README.md+├── backend/ # Full Rails app — the Spree API (from spree/spree-starter)+│ ├── Gemfile+│ ├── Dockerfile # Also builds the production image (API + dashboard)+│ ├── config/+│ ├── app/+│ └── ...+└── apps/+ ├── storefront/ # Next.js storefront (unless --no-storefront)+ │ ├── .env.local # API URL + API key+ │ └── ...+ └── dashboard/ # React Dashboard (with --react-dashboard)+ ├── .env.local # Dev proxy target — no credentials+ └── ...+```++### What's in docker-compose.yml++- **Spree** — one `web` container running the `ghcr.io/spree/spree:latest` image on the configured port (default `3000`); background jobs run in-process via Solid Queue (stored in Postgres — job dashboard at `/jobs`)+- **PostgreSQL 18** — database with persistent volume+- **Meilisearch** — search engine+- Health checks on postgres, meilisearch, and web++## Customizing the Spree API++The `backend/` directory is the Spree API — a full Rails application with Spree installed (cloned from [spree-starter](https://github.com/spree/spree-starter)) serving the Store and Admin APIs your storefront and dashboard talk to, plus background jobs and transactional emails. By default, the project runs it from a prebuilt Docker image. To switch to building from your local copy:++```bash+npx spree eject+```++This replaces `docker-compose.yml` with a version that builds from `backend/`, rebuilds the image, and restarts services. You can then:++- **Add gems** to `backend/Gemfile`+- **Override models** with decorators in `backend/app/models/`+- **Add controllers** in `backend/app/controllers/`+- **Configure Spree** in `backend/config/initializers/spree.rb`+- **Add migrations** with `spree generate migration AddFooToSpreeBars foo:string` (runs inside the container)++See the [Customization Guide](/developer/customization) for more details.++### Spree CLI Commands++The project includes [@spree/cli](/v5/developer/cli/quickstart) for managing your Spree backend:++| Command | Description |+|---------|-------------|+| `spree dev` | Run the app in the foreground — streams logs, Ctrl+C stops it. First run completes setup automatically; co-runs the React Dashboard dev server when `apps/dashboard` exists |+| `spree stop` | Stop backend services |+| `spree update` | Pull latest Spree image and restart (runs migrations automatically) |+| `spree eject` | Switch from prebuilt image to building from `backend/` |+| `spree add dashboard` | Add the React Dashboard to an existing project |+| `spree build --production` | Build the production image — the Spree API plus your dashboard, in one |+| `spree logs` | View backend logs |+| `spree logs worker` | View background jobs logs |+| `spree console` | Rails console |++## After Setup++### Admin Dashboard++Open [http://localhost:3000/admin](http://localhost:3000/admin) and log in with:++| | |+|---|---|+| **Email** | `[email protected]` |+| **Password** | `spree123` |++With `--react-dashboard`, the React Dashboard's dev server is the admin instead: `spree dev` starts it alongside the API at [http://localhost:5173](http://localhost:5173) — same credentials, live-reloading from `apps/dashboard/` (the classic admin remains at `/admin`). See the [React Dashboard docs](/v5/developer/dashboard/overview).++### Store API++The REST API is available at [http://localhost:3000/api/v3/store](http://localhost:3000/api/v3/store). See the [API Reference](/api-reference) for details.++### Storefront++If you included the storefront, start it in a separate terminal:++```bash+cd my-store/apps/storefront+npm run dev+```++Open [http://localhost:3001](http://localhost:3001) to see your store.++## Updating Spree++To update to the latest Spree version:++```bash+spree update+```++This pulls the latest Docker image and recreates the containers. The entrypoint automatically runs database migrations.++To pin a specific version, edit `SPREE_VERSION_TAG` in `.env`:++```+SPREE_VERSION_TAG=5.4+```++## Deployment++The project deploys as **one image**: `backend/Dockerfile` builds the Spree API together with your React Dashboard (when `apps/dashboard` exists), served same-origin at `/dashboard` — no CORS, no cookie configuration, no second service.++- **Render** — the `render.yaml` at the project root is a ready Blueprint: one Docker service built straight from your repo, migrations run on boot.+- **Anywhere else** — `spree build --production` builds the same image locally; push it to a registry and run it on any Docker host.++See the [Deployment Guide](/developer/deployment) and the [dashboard deployment docs](/v5/developer/dashboard/deployment).++## Next Steps++<CardGroup cols={2}>+ <Card title="Next.js Storefront" icon="react" href="/developer/storefront/nextjs/quickstart">+ Customize and extend the Storefront+ </Card>+ <Card title="Spree SDK" icon="code" href="/developer/sdk/quickstart">+ TypeScript SDK for the Store and Admin APIs+ </Card>+ <Card title="API Reference" icon="book" href="/api-reference">+ Explore the REST API endpoints+ </Card>+ <Card title="Core Concepts" icon="brain" href="/developer/core-concepts/architecture">+ Learn about Spree's architecture+ </Card>+</CardGroup>diff --git a/docs/v6/developer/customization/api.mdx b/docs/v5/developer/customization/api.mdxsimilarity index 74%rename from docs/v6/developer/customization/api.mdxrename to docs/v5/developer/customization/api.mdxindex 6c236d778e..2a3f460ba4 100644--- a/docs/v6/developer/customization/api.mdx+++ b/docs/v5/developer/customization/api.mdx@@ -1,11 +1,12 @@---title: Customizing the Spree APIdescription: Add new Store API endpoints, customize existing JSON responses with serializer decorators, and extend Spree's REST API to fit your storefront needs.+canonical: "https://spreecommerce.org/docs/developer/customization/api"---Before you start customizing Spree API endpoints, make sure you reviewed all existing API endpoints in the [Spree API docs](/api-reference/admin-api/endpoints).-For a step-by-step walkthrough of adding a complete new resource (model, serializer, controller, routes), see the [API tutorial](/developer/tutorial/api).+For a step-by-step walkthrough of adding a complete new resource (model, serializer, controller, routes), see the [API tutorial](/v5/developer/tutorial/api).## Customizing JSON Responses@@ -35,7 +36,7 @@ Restart the server and the Product API will include your new attribute.### Adding an Association-Let's say you've created a `Spree::Brand` model that belongs to `Product` (see the [tutorial](/developer/tutorial/api) for the full example).+Let's say you've created a `Spree::Brand` model that belongs to `Product` (see the [tutorial](/v5/developer/tutorial/api) for the full example).Create a serializer for the new model:@@ -173,49 +174,20 @@ end### Permitted Attributes-For endpoints that accept writes (create/update), declare the attributes in your-controller:--```ruby-def resource_permitted_attributes- [:name, :slug, :description, :logo]-end-```--Entries are `params.permit` fragments, so collections and nested structures use-the shapes you would pass there directly — `[:name, { region_ids: [] }]`.--<Note>- Declare `resource_permitted_attributes`, not `permitted_attributes`. The- latter is what appends extension-contributed attributes to your list, so- overriding it replaces them.-</Note>--### Adding an Attribute to a Core Resource--To make a new column writable on a Spree model without decorating the-controllers that write it, append to the model's permitted attributes:+For endpoints that accept writes (create/update), add your attributes:```ruby config/initializers/spree.rb-Spree::Product.additional_permitted_attributes += [:brand_id]+Spree::PermittedAttributes.brand_attributes = [:name, :slug, :description, :logo]```-Standard resource endpoints append these to their own allowlist, so one-declaration covers the model's create and update endpoints.--Use `+=`, never `=` — assigning replaces what another extension added — and-declare only attributes of your own, since redeclaring a key the controller-already permits replaces its filter rather than widening it.--<Note>- For merchant-managed data, prefer [Custom Fields](/developer/core-concepts/metafields),- which need no code and are filterable and sortable. This is for extensions- that add real database columns.-</Note>+Or override `permitted_params` in the controller:-Two endpoints deliberately ignore this hook because their parameters are-authorization data rather than resource data: API keys and invitations.+```ruby+def permitted_params+ params.permit(:name, :slug, :description, :logo)+end+```## Consuming Custom Endpoints with the SDK-See the [SDK tutorial](/developer/tutorial/sdk) for how to call custom endpoints from TypeScript and extend the generated types.+See the [SDK tutorial](/v5/developer/tutorial/sdk) for how to call custom endpoints from TypeScript and extend the generated types.diff --git a/docs/developer/customization/authentication.mdx b/docs/v5/developer/customization/authentication.mdxsimilarity index 94%rename from docs/developer/customization/authentication.mdxrename to docs/v5/developer/customization/authentication.mdxindex ae7bb11d99..eaa55b2255 100644--- a/docs/developer/customization/authentication.mdx+++ b/docs/v5/developer/customization/authentication.mdx@@ -2,6 +2,7 @@title: Authenticationdescription: Integrate Spree with a custom authentication setup, including Devise, an existing user model, OmniAuth providers, and JWT or OAuth API tokens.version: v5+canonical: "https://spreecommerce.org/docs/v5/developer/customization/authentication"---If you installed Spree following the [Quickstart guide](/developer/quickstart), you can completely skip this step - you are all set and integrated with the [Devise](https://github.com/plataformatec/devise) gem.@@ -101,4 +102,4 @@ end## Admin Panel authentication-Please refer to the [Admin Panel Authentication](/developer/admin/authentication) page for more details.+Please refer to the [Admin Panel Authentication](/v5/developer/admin/authentication) page for more details.diff --git a/docs/developer/customization/checkout.mdx b/docs/v5/developer/customization/checkout.mdxsimilarity index 92%rename from docs/developer/customization/checkout.mdxrename to docs/v5/developer/customization/checkout.mdxindex 119026f7a4..c03db73693 100644--- a/docs/developer/customization/checkout.mdx+++ b/docs/v5/developer/customization/checkout.mdx@@ -2,6 +2,7 @@title: Checkout Flowdescription: Customize the Spree checkout flow with the checkout DSL — add, remove, or conditionally skip address, delivery, payment, and confirmation steps.version: v5+canonical: "https://spreecommerce.org/docs/v5/developer/customization/checkout"---## Overview@@ -40,7 +41,7 @@ If you want a list of all the currently available states for the checkout, use t## Default Checkout Steps-The Spree checkout process consists of the following steps. With the exception of the Registration step, each of these steps corresponds to a state of the [Order object](/developer/core-concepts/orders):+The Spree checkout process consists of the following steps. With the exception of the Registration step, each of these steps corresponds to a state of the [Order object](/v5/developer/core-concepts/orders):* Shipping Address and Contact Information* Delivery Options Shipping Method@@ -55,7 +56,7 @@ This step allows the customer to add shipping information and contact informatioThe address fields include a select box for choosing state/province. If there are no states configured for a particular country, the select box will be replaced by a text field instead.-The list of countries that appear in the country select box can also be configured. Spree will list all countries by default, but you can configure exactly which countries you would like to appear. The list can be limited to a specific set of countries by [setting the Store's checkout zone](/developer/core-concepts/stores#checkout-configuration).+The list of countries that appear in the country select box can also be configured. Spree will list all countries by default, but you can configure exactly which countries you would like to appear. The list can be limited to a specific set of countries by [setting the Store's checkout zone](/v5/developer/core-concepts/stores#checkout-configuration).### Delivery Options@@ -67,7 +68,7 @@ This step is where the customer provides payment and billing information. SpreeBesides Credit Card, Wallets and other 3rd party payment methods, Spree also supports Store Credit and Gift Cards (Spree 5.1+ only) which can be used to pay for the entire order or part of the order.-For more information about payments, please see the [Payments guide](/developer/core-concepts/payments).+For more information about payments, please see the [Payments guide](/v5/developer/core-concepts/payments).### Confirmation@@ -81,7 +82,7 @@ This step is disabled by default, but can be enabled by two ways:Spree::Config[:always_include_confirm_step] = true```-2. conditionally for specific orders by overriding the `confirmation_required?` method in `Spree::Order` with a [decorator](/developer/customization/decorators), eg.+2. conditionally for specific orders by overriding the `confirmation_required?` method in `Spree::Order` with a [decorator](/v5/developer/customization/decorators), eg.```ruby app/models/spree/order_decorator.rbmodule Spree@@ -100,7 +101,7 @@ There are two approaches for adding logic around checkout state transitions:### Approach 1: Events Subscribers (Recommended for side effects)-For actions that should happen **after** a checkout step completes (syncing with external services, sending notifications, logging, etc.), use [Events subscribers](/developer/core-concepts/events). This is the recommended approach because it keeps your code decoupled from Spree internals.+For actions that should happen **after** a checkout step completes (syncing with external services, sending notifications, logging, etc.), use [Events subscribers](/v5/developer/core-concepts/events). This is the recommended approach because it keeps your code decoupled from Spree internals.```ruby app/subscribers/order_completed_subscriber.rbclass OrderCompletedSubscriber < Spree::Subscriber@@ -118,7 +119,7 @@ end```<Info>- Events are fired automatically when orders change state. See [Events documentation](/developer/core-concepts/events#order-events) for all available order events.+ Events are fired automatically when orders change state. See [Events documentation](/v5/developer/core-concepts/events#order-events) for all available order events.</Info>### Approach 2: State Machine Callbacks (For validation/blocking logic)@@ -147,7 +148,7 @@ endThis callback would prevent transitioning to the `delivery` step if `valid_zip_code?` returns false.<Warning>- Avoid using state machine callbacks for side effects like API calls or notifications. These can slow down checkout and may fail silently. Use [Events subscribers](/developer/core-concepts/events) instead.+ Avoid using state machine callbacks for side effects like API calls or notifications. These can slow down checkout and may fail silently. Use [Events subscribers](/v5/developer/core-concepts/events) instead.</Warning>## Modifying the checkout flowdiff --git a/docs/v5/developer/customization/configuration.mdx b/docs/v5/developer/customization/configuration.mdxnew file mode 100644index 0000000000..ccc2592496--- /dev/null+++ b/docs/v5/developer/customization/configuration.mdx@@ -0,0 +1,58 @@+---+title: "Configuration"+canonical: "https://spreecommerce.org/docs/developer/customization/configuration"+---++Here is a list of all the configuration options that are available in Spree.++ | Configuration Key | Description | Default Value |+ |------------------------------------|-------------------------------------------------------------------------------------------------------|---------------------|+ | `allow_checkout_on_gateway_error` | Continues the checkout process even if the payment gateway error failed. | `false` |+ | `address_requires_phone` | Determines whether a phone number is required for Addresses. | `false` |+ | `alternative_shipping_phone` | Determines if an alternative phone number should be present for the shipping address on the checkout page. | `false` |+ | `always_include_confirm_step` | Determines if the confirmation step is always included in the checkout process, regardless of the payment method. | `false` |+ | `auto_capture` | Depending on whether or not Spree is configured to "auto capture" the credit card, either a purchase or an authorize operation will be performed on the card (via the current credit card gateway). | `true` |+ | `auto_capture_on_dispatch` | Captures payment for each shipment in Shipment#after_ship callback, and makes Shipment.ready when payment authorized. | `false` |+ | `company` | Determines whether or not a field for "Company" displays on the address form. | `false` |+ | `credit_to_new_allocation` | Determines if a new allocation is created anytime store credit is added. If not set, it will update the store credit's amount in place. | `false` |+ | `disable_sku_validation` | Determines if the built-in SKU uniqueness validation is disabled. | `false` |+ | `disable_store_presence_validation` | Determines if Store presence validation for Products and Payment Methods is disabled. | `false` |+ | `expedited_exchanges` | Determines if an exchange shipment is kicked off upon return authorization save. Requires payment profiles to be supported on your gateway and a configured delayed job handler. | `false` |+ | `expedited_exchanges_days_window` | The number of days the customer has to return their item after the expedited exchange is shipped to avoid being charged. | `14` |+ | `restock_inventory` | Determines if inventory should be restocked when an order is canceled or returned | `true` |+ | `return_eligibility_number_of_days` | The number of days after purchase within which a return can be initiated. | `365` |+ | `show_products_without_price` | Determines if products without a price are shown in the storefront and Storefront API | `false` |+ | `tax_using_ship_address` | Determines if tax information should be based on shipping address, rather than the billing address. | `true` |+ | `track_inventory_levels` | Determines if inventory levels should be tracked when products are purchased at checkout. This option causes new `InventoryUnit` objects to be created when a product is bought. | `true` |++## Spree Initializer++To change values for these preferences, you need to edit your `config/initializers/spree.rb` file.++For example, to disable the `expedited_exchanges` feature, you would add the following line:++```ruby+Spree.config do |config|+ config.expedited_exchanges = false+end+```++<Note>+ Remember to restart your Rails server after making changes to the `config/initializers/spree.rb` file.+</Note>++## Accessing Configuration++To access these preferences in your application, you can use the `Spree::Config` module. For example, to access the `expedited_exchanges` preference, you can do the following:++```ruby+Spree::Config.expedited_exchanges+```++This will return the current value of the `expedited_exchanges` preference. You can also set the value of a preference using the `Spree::Config` module. For example, to set the `expedited_exchanges` preference to `true`, you can do the following:++```ruby+Spree::Config.expedited_exchanges = true+```++This will set the `expedited_exchanges` preference to `true` for the current process. After restarting the Rails server, the preference will return to the default value or the one set in the initializer.diff --git a/docs/v5/developer/customization/decorators.mdx b/docs/v5/developer/customization/decorators.mdxnew file mode 100644index 0000000000..8072137f70--- /dev/null+++ b/docs/v5/developer/customization/decorators.mdx@@ -0,0 +1,567 @@+---+title: Decorators+description: Use Spree decorators to add or modify behavior on core models, controllers, and helpers without forking the gem — patterns, file layout, and pitfalls.+canonical: "https://spreecommerce.org/docs/developer/customization/decorators"+---++<Warning>+ **Decorators should be a last resort.** They tightly couple your code to Spree internals and can break during upgrades. Before using decorators, consider these modern alternatives that are safer and easier to maintain:++ - **[Events & Subscribers](/v5/developer/core-concepts/events)** - For reacting to model changes (after save, create, update, delete)+ - **[Webhooks](/v5/developer/core-concepts/webhooks)** - For notifying external services when events occur+ - **[Dependencies](/v5/developer/customization/dependencies)** - For swapping out services, serializers, and abilities+ - **[Admin Navigation](/v5/developer/admin/navigation)** - For adding menu items without controller decorators+ - **[Admin Partials](/v5/developer/admin/extending-ui)** - For extending admin UI without view decorators+ - **[Admin Tables](/v5/developer/admin/tables)** - For customizing admin list views+ - **[Ransack Configuration](/v5/developer/core-concepts/search-filtering#extending-ransackable-configuration)** - For adding searchable/sortable fields without model decorators+</Warning>++## When to Use Decorators vs Modern Alternatives++Before reaching for a decorator, check if your use case is better served by a modern alternative:++| Use Case | Instead of Decorator | Use This |+|----------|---------------------|----------|+| After-save hooks (sync to external service) | Model decorator with `after_save` | [Events subscriber](/v5/developer/core-concepts/events) |+| Notify external service on changes | Model decorator with callbacks | [Webhooks](/v5/developer/core-concepts/webhooks) |+| Custom add-to-cart logic | Service decorator | [Dependencies injection](/v5/developer/customization/dependencies) |+| Custom API responses | Serializer decorator | [Dependencies injection](/v5/developer/customization/dependencies) |+| Add admin menu item | Controller decorator | [Admin Navigation API](/v5/developer/admin/navigation) |+| Add section to admin form | View decorator/override | [Admin Partials injection](/v5/developer/admin/extending-ui) |+| Add searchable/filterable field | Model decorator with `ransackable_attributes` | [Ransack configuration](/v5/developer/core-concepts/search-filtering#extending-ransackable-configuration) |+| 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) |++<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.+</Info>++## Overview++All of Spree's models, controllers, helpers, etc can easily be extended or overridden to meet your exact 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.++## Why Use Decorators?++When working with Spree, you'll often need to add functionality to existing models like `Spree::Product` or `Spree::Order`. However, you shouldn't modify these files directly because:++1. **Upgrades** - Your changes would be lost when updating Spree+2. **Maintainability** - It's hard to track what you've customized+3. **Conflicts** - Direct modifications can conflict with Spree's code++Instead, we use **decorators** - a Ruby pattern that lets you add or modify behavior of existing classes without changing their original source code.++## How Decorators Work++In Ruby, classes are "open" - you can add methods to them at any time. Decorators leverage this by:++1. Creating a module with your new methods+2. Using `Module#prepend` to inject your module into the class's inheritance chain+3. Your methods run first, and can call `super` to invoke the original method++```ruby+# This is the basic pattern+module Spree+ module ProductDecorator+ # Add a new method+ def my_new_method+ "Hello from decorator!"+ end++ # Override an existing method+ def existing_method+ # Do something before+ result = super # Call the original method+ # Do something after+ result+ end+ end++ Product.prepend(ProductDecorator)+end+```++The key line is `Product.prepend(ProductDecorator)` - this inserts your module at the beginning of the method lookup chain, so your methods are found first.++## Generating Decorators++Spree provides generators to create decorator files with the correct structure:++### Model Decorator Generator++<CodeGroup>++```bash Spree CLI (Docker)+spree generate spree:model_decorator Spree::Product+```++```bash Without Spree CLI+bin/rails g spree:model_decorator Spree::Product+```++</CodeGroup>++This creates `app/models/spree/product_decorator.rb`:++```ruby+module Spree+ module ProductDecorator+ def self.prepended(base)+ # Class-level configurations go here+ end+ end++ Product.prepend(ProductDecorator)+end+```++### Controller Decorator Generator++<CodeGroup>++```bash Spree CLI (Docker)+spree generate spree:controller_decorator Spree::Admin::ProductsController+```++```bash Without Spree CLI+bin/rails g spree:controller_decorator Spree::Admin::ProductsController+```++</CodeGroup>++This creates `app/controllers/spree/admin/products_controller_decorator.rb`:++```ruby+module Spree::Admin+ module ProductsControllerDecorator+ def self.prepended(base)+ # base.before_action :my_filter+ end++ # add custom methods here+ end+end++Spree::Admin::ProductsController.prepend Spree::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.++## Decorating Models++### Changing Behavior of Existing Methods++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+module Spree+ module ProductDecorator+ def available?+ # Add custom logic before+ return false if discontinued?++ # Call the original method+ super+ end+ end++ Product.prepend(ProductDecorator)+end+```++<Warning>+ Always consider whether you need to call `super` when overriding methods. Omitting it completely replaces the original behavior, which may break functionality.+</Warning>++### Adding New Methods++Add new instance methods directly in the decorator module:++```ruby app/models/spree/product_decorator.rb+module Spree+ module ProductDecorator+ def featured?+ metadata[:featured] == true+ end++ def days_until_available+ return 0 if available_on.nil? || available_on <= Time.current+ (available_on.to_date - Date.current).to_i+ end+ end++ Product.prepend(ProductDecorator)+end+```++### Adding Associations++Use the `self.prepended(base)` callback to add associations:++```ruby app/models/spree/product_decorator.rb+module Spree+ module ProductDecorator+ def self.prepended(base)+ base.belongs_to :brand, class_name: 'Spree::Brand', optional: true+ base.has_many :videos, class_name: 'Spree::Video', dependent: :destroy+ end+ end++ Product.prepend(ProductDecorator)+end+```++### Adding Validations++```ruby app/models/spree/product_decorator.rb+module Spree+ module ProductDecorator+ def self.prepended(base)+ base.validates :external_id, presence: true, uniqueness: true+ base.validates :weight, numericality: { greater_than: 0 }, allow_nil: true+ end+ end++ Product.prepend(ProductDecorator)+end+```++### Adding Scopes++```ruby app/models/spree/product_decorator.rb+module Spree+ module ProductDecorator+ def self.prepended(base)+ base.scope :featured, -> { where("metadata->>'featured' = ?", 'true') }+ base.scope :recently_added, -> { where('created_at > ?', 30.days.ago) }+ base.scope :on_sale, -> { joins(:variants).where('spree_prices.compare_at_amount > spree_prices.amount') }+ end+ end++ Product.prepend(ProductDecorator)+end+```++### Adding Class Methods++Use `extend` within the `prepended` callback to add class methods:++```ruby app/models/spree/product_decorator.rb+module Spree+ module ProductDecorator+ def self.prepended(base)+ base.extend ClassMethods+ end++ module ClassMethods+ def search_by_name(query)+ where('LOWER(name) LIKE ?', "%#{query.downcase}%")+ end+ end+ end++ Product.prepend(ProductDecorator)+end+```++Usage:++```ruby+Spree::Product.search_by_name('shirt')+```++## Decorating Controllers++<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.+</Warning>++### Recommended: Create a New Controller++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+```++```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+```++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+ module ProductsControllerDecorator+ def self.prepended(base)+ base.before_action :load_product, only: [:quick_view]+ end++ def quick_view+ respond_to do |format|+ format.html { render partial: 'quick_view', locals: { product: @product } }+ format.json { render json: @product }+ end+ end++ private++ def load_product+ @product = current_store.products.friendly.find(params[:id])+ 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+```++### Modifying Existing Actions++<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](/v5/developer/core-concepts/events) for post-action side effects instead.+</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++ # Add custom logic after+ notify_team_of_new_product if @product.persisted?+ end++ private++ def log_product_creation_attempt+ Rails.logger.info "Product creation attempted by #{current_spree_user.email}"+ end++ def notify_team_of_new_product+ ProductNotificationJob.perform_later(@product)+ end+ end++ ProductsController.prepend(ProductsControllerDecorator)+ end+end+```++<Info>+ **Better alternative:** For post-action side effects like notifications, use [Events subscribers](/v5/developer/core-concepts/events) instead. Subscribe to `product.created` to be notified when products are created, without coupling to controller internals.+</Info>++### Adding Before Actions++```ruby app/controllers/spree/checkout_controller_decorator.rb+module Spree+ module CheckoutControllerDecorator+ def self.prepended(base)+ base.before_action :check_minimum_order, only: [:update]+ 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+ end+ end++ CheckoutController.prepend(CheckoutControllerDecorator)+end+```++## Best Practices++<CardGroup cols={2}>+ <Card title="Use the prepended callback" icon="code">+ Always use `self.prepended(base)` for class-level additions like associations, validations, scopes, and callbacks.+ </Card>++ <Card title="Keep decorators focused" icon="crosshairs">+ Each decorator should have a single responsibility. Create multiple decorators for different concerns if needed.+ </Card>++ <Card title="Call super when overriding" icon="arrow-up">+ When overriding methods, call `super` to preserve original behavior unless you intentionally want to replace it entirely.+ </Card>++ <Card title="Test decorated behavior" icon="flask-vial">+ Write tests specifically for your decorated functionality to catch regressions during upgrades.+ </Card>+</CardGroup>++### Organizing Multiple Decorators++If you have many customizations for a single class, consider splitting them into focused decorators:++```+app/models/spree/+├── product_decorator.rb # Main decorator (loads others)+├── product/+│ ├── brand_decorator.rb # Brand association+│ ├── inventory_decorator.rb # Inventory customizations+│ └── 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'+```++## Common Pitfalls++### Forgetting to Call Super++```ruby+# ❌ Bad - completely replaces original behavior+def available?+ in_stock? && active?+end++# ✅ Good - extends original behavior+def available?+ super && custom_availability_check+end+```++### Using Instance Variables in prepended++```ruby+# ❌ Bad - instance variables don't work in prepended+def self.prepended(base)+ @custom_setting = true # This won't work as expected+end++# ✅ Good - use class attributes or methods+def self.prepended(base)+ base.class_attribute :custom_setting, default: true+end+```++### Circular Dependencies++Be careful when decorators depend on each other:++```ruby+# ❌ Bad - can cause loading issues+# product_decorator.rb+def self.prepended(base)+ base.has_many :variants # Variant decorator might not be loaded yet+end++# ✅ Good - use strings for class names+def self.prepended(base)+ base.has_many :variants, class_name: 'Spree::Variant'+end+```++## Migrating from Decorators to Modern Patterns++If you have existing decorators that use callbacks for side effects, consider migrating them to Events subscribers for better maintainability.++### Example: Migrating an After-Save Callback++**Before (Decorator with callback):**++```ruby app/models/spree/product_decorator.rb+module Spree+ module ProductDecorator+ def self.prepended(base)+ base.after_save :sync_to_external_service+ end++ private++ def sync_to_external_service+ ExternalSyncJob.perform_later(self) if saved_change_to_name?+ end+ end++ Product.prepend(ProductDecorator)+end+```++**After (Events subscriber):**++```ruby app/subscribers/product_sync_subscriber.rb+class ProductSyncSubscriber < Spree::Subscriber+ subscribes_to 'product.updated'++ def handle(event)+ 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+ end+end+```++### Benefits of Migration++<CardGroup cols={2}>+ <Card title="Loose coupling" icon="link-slash">+ Your code doesn't depend on Spree internals. Events provide a stable interface.+ </Card>++ <Card title="Easier upgrades" icon="arrow-up">+ Events-based code is less likely to break when Spree is updated.+ </Card>++ <Card title="Better testability" icon="flask-vial">+ Subscribers can be tested in isolation without loading the full model.+ </Card>++ <Card title="Async by default" icon="bolt">+ Subscribers run via ActiveJob, keeping your requests fast.+ </Card>+</CardGroup>++## Related Documentation++- [Events](/v5/developer/core-concepts/events) - Learn about Spree's event system+- [Webhooks](/v5/developer/core-concepts/webhooks) - HTTP callbacks for external integrations+- [Dependencies](/v5/developer/customization/dependencies) - Swap core services with your own+- [Admin Navigation](/v5/developer/admin/navigation) - Extend admin menu without decorators+- [Admin Partials](/v5/developer/admin/extending-ui) - Extend admin UI without view decorators+- [Extending Core Models Tutorial](/v5/developer/tutorial/extending-models) - Step-by-step guide to connecting custom models with Spree core+- [Customization Overview](/v5/developer/customization/quickstart) - General customization patternsdiff --git a/docs/v6/developer/customization/dependencies.mdx b/docs/v5/developer/customization/dependencies.mdxsimilarity index 93%rename from docs/v6/developer/customization/dependencies.mdxrename to docs/v5/developer/customization/dependencies.mdxindex 39bf7f4d66..b514d27e41 100644--- a/docs/v6/developer/customization/dependencies.mdx+++ b/docs/v5/developer/customization/dependencies.mdx@@ -1,20 +1,21 @@---title: Dependenciessection: customization+canonical: "https://spreecommerce.org/docs/developer/customization/dependencies"---## OverviewWith Dependencies, you can replace parts of Spree core with your custom code:-[Services and Workflows](/developer/customization/workflows), CanCanCan-Abilities (used for [Permissions](/developer/customization/permissions)), and API Serializers (used for+[Services and Workflows](/v5/developer/customization/workflows), CanCanCan+Abilities (used for [Permissions](/v5/developer/customization/permissions)), and API Serializers (used forgenerating JSON API responses).<Tip>Replacing a whole class means keeping your copy in sync with every Spreerelease. If you only need to run code inside an existing flow — validating,reacting, or contributing data to a calculation — use a-[hook](/developer/customization/workflows#extending-a-workflow-with-hooks)+[hook](/v5/developer/customization/workflows#extending-a-workflow-with-hooks)instead. Hooks survive upgrades.</Tip>@@ -84,7 +85,7 @@ Spree.cart_add_item_workflow = MyStore::AddItem<Note>Before writing this, check whether a-[hook](/developer/customization/workflows#available-hooks) covers your case —+[hook](/v5/developer/customization/workflows#available-hooks) covers your case —`carts.add_item.validate` and `carts.add_item.after_item_added` handle mostreasons people replace this class, and they don't need maintaining acrossupgrades.@@ -104,7 +105,7 @@ Spree.api.storefront_cart_serializer.new(order).serializable_hash## Controller level customization-If you need to replace [serializers](https://github.com/jsonapi-serializer/jsonapi-serializer) or Services in a specific API endpoint you can create a [code decorator](/developer/customization/decorators):+If you need to replace [serializers](https://github.com/jsonapi-serializer/jsonapi-serializer) or Services in a specific API endpoint you can create a [code decorator](/v5/developer/customization/decorators):```bashmkdir -p app/controllers/spree && touch app/controllers/spree/cart_controller_decorator.rb@@ -239,7 +240,7 @@ Spree::Dependencies.validate!## Renamed seams in Spree 6.0-Seams backed by a [workflow](/developer/customization/workflows) were renamed+Seams backed by a [workflow](/v5/developer/customization/workflows) were renamedfrom `*_service` to `*_workflow` in 6.0:| Legacy name | Current name |diff --git a/docs/developer/customization/emails.mdx b/docs/v5/developer/customization/emails.mdxsimilarity index 91%rename from docs/developer/customization/emails.mdxrename to docs/v5/developer/customization/emails.mdxindex 52f9e34685..56eccc50ed 100644--- a/docs/developer/customization/emails.mdx+++ b/docs/v5/developer/customization/emails.mdx@@ -1,6 +1,7 @@---title: Emailsdescription: Customize Spree transactional emails using the spree_emails gem and Postmark templates, including how to preview mailers locally during development.+canonical: "https://spreecommerce.org/docs/v5/developer/customization/emails"---<Note>diff --git a/docs/v5/developer/customization/metadata.mdx b/docs/v5/developer/customization/metadata.mdxnew file mode 100644index 0000000000..e046f99018--- /dev/null+++ b/docs/v5/developer/customization/metadata.mdx@@ -0,0 +1,250 @@+---+title: Metadata+canonical: "https://spreecommerce.org/docs/developer/customization/metadata"+---++## Overview++Metadata provides simple, unstructured key-value storage on Spree resources — similar to [Stripe's metadata](https://docs.stripe.com/api/metadata). It's ideal for storing integration IDs, tracking data, or any arbitrary information that doesn't need validation or admin UI.++Metadata is a **permanent, first-class system** in Spree. It is designed to coexist alongside [Metafields](/v5/developer/core-concepts/metafields) (structured, typed, admin-managed). The two systems serve different purposes and are not interchangeable — think of it as **metadata for machines, metafields for humans**.++Metadata is **write-only** in the Store API — you can set it when creating or updating resources, but it is never returned in Store API responses. It is visible in Admin API responses for administrative use.++<Info>+For structured, type-safe custom attributes with admin UI support, use [Metafields](/v5/developer/core-concepts/metafields) instead.+</Info>++## Store API++### Cart creation++Set metadata when creating a new cart:++```bash+POST /api/v3/store/carts+Content-Type: application/json++{+ "metadata": {+ "source": "mobile_app",+ "campaign": "summer_sale"+ }+}+```++```typescript+// @spree/sdk+const cart = await client.carts.create({+ metadata: { source: 'mobile_app', campaign: 'summer_sale' }+})++```++### Adding items++Set metadata when adding items to the cart:++```bash+POST /api/v3/store/carts/:cart_id/items+Content-Type: application/json++{+ "variant_id": "variant_k5nR8xLq",+ "quantity": 1,+ "metadata": {+ "gift_note": "Happy Birthday!",+ "engraving": "J.D."+ }+}+```++```typescript+const order = await client.carts.items.create(cartId, {+ variant_id: 'variant_k5nR8xLq',+ quantity: 1,+ metadata: { gift_note: 'Happy Birthday!' },+})+```++### Updating items++Metadata is **merged** with existing values on update. Set a key to `null` to remove it.++```bash+PATCH /api/v3/store/carts/:cart_id/items/:id+Content-Type: application/json++{+ "metadata": {+ "engraving": "A.B.",+ "gift_note": null+ }+}+```++You can update metadata without changing quantity, or update both at once:++```typescript+// Metadata only+await client.carts.items.update(cartId, lineItemId, {+ metadata: { engraving: 'A.B.' },+})++// Both quantity and metadata+await client.carts.items.update(cartId, lineItemId, {+ quantity: 3,+ metadata: { gift_note: 'Happy Birthday!' },+})+```++### Updating carts++```bash+PATCH /api/v3/store/carts/:id+Content-Type: application/json++{+ "metadata": {+ "utm_source": "google",+ "utm_campaign": "summer_sale"+ }+}+```++```typescript+await client.carts.update(cartId, {+ metadata: { utm_source: 'google' },+}, { spreeToken })+```++## Admin API++Metadata is **readable** in Admin API responses on orders and line items:++```json+{+ "id": "or_m3Rp9wXz",+ "number": "R123456",+ "metadata": {+ "source": "mobile_app",+ "utm_campaign": "summer_sale"+ },+ "items": [+ {+ "id": "li_x8Kp2qWz",+ "metadata": {+ "gift_note": "Happy Birthday!"+ }+ }+ ]+}+```++When there is no metadata, the field is `null`.++## Ruby / Backend++### Reading and writing++Every model that includes `Spree::Metadata` has a `metadata` accessor. Always use `metadata` in Ruby code — do not call `public_metadata=` or `private_metadata=` directly. (SQL queries still reference the underlying `private_metadata` column name — see querying examples below.)++```ruby+order = Spree::Order.find_by!(number: 'R123456')++# Write+order.metadata = { 'source' => 'mobile_app' }+order.save!++# Read+order.metadata['source'] # => "mobile_app"++# Merge+order.metadata = order.metadata.merge('campaign' => 'summer')+order.save!+```++### Querying++```ruby+# Find orders with specific metadata value (PostgreSQL)+Spree::Order.where("private_metadata->>'source' = ?", "mobile_app")++# Check for key existence+Spree::Order.where("private_metadata ? 'source'")+```++## Merge semantics++Metadata updates use **merge semantics** — existing keys are preserved, new keys are added, and keys set to `null` are removed. This matches [Stripe's behavior](https://docs.stripe.com/api/metadata).++```+# Initial metadata+{ "source": "mobile_app", "campaign": "summer" }++# Update with+{ "campaign": "winter", "new_key": "value" }++# Result+{ "source": "mobile_app", "campaign": "winter", "new_key": "value" }+```++## Metadata vs Metafields++Spree has two permanent, complementary systems for custom data. They are not interchangeable and neither is going away.++| | Metadata | [Metafields](/v5/developer/core-concepts/metafields) |+|---|---|---|+| **Purpose** | Developer escape hatch — integration data, sync state, ad-hoc flags | Merchant-defined structured attributes with admin UI |+| **Schema** | Schemaless JSON — no definition required | Defined via MetafieldDefinitions (typed, validated) |+| **Validation** | None — accepts any JSON-serializable data | Type-specific (text, number, boolean, rich text, JSON) |+| **Visibility** | Write-only in Store API, readable in Admin API | Configurable (front-end, back-end, both) |+| **Admin UI** | JSON preview only | Dedicated management forms |+| **API pattern** | Stripe-style: `metadata: { key: value }` | Expand-based: `?expand=custom_fields` |+| **Queryable** | Via JSONB operators (PostgreSQL) | Via SQL joins, Ransack scopes, search providers |++### When to use metadata++- Storing external system IDs (e.g., Stripe payment intent ID, ERP order ID)+- Tracking attribution data (UTM parameters, referral source)+- Passing context from the storefront that doesn't need validation+- Any write-and-forget data that only needs to be read by backend systems+- Syncing state with external integrations (webhooks, ETL pipelines)++### When to use metafields++- Custom product specifications shown to customers (material, dimensions, certifications)+- Admin-managed fields with validation and type safety+- Data that needs to appear in the admin UI with dedicated form inputs+- Querying/filtering by custom attributes (search facets, product filtering)+- CSV import/export of structured product data++## Supported resources++All models that include the `Spree::Metadata` concern support metadata. This includes all core models: Orders, Line Items, Products, Variants, Taxons, Payments, Shipments, and more.++The Store API currently supports writing metadata on:++- **Carts** — on creation and update (`POST /api/v3/store/carts`, `PATCH /api/v3/store/carts/:id`)+- **Items** — on create and update (`POST/PATCH /api/v3/store/carts/:id/items`)++## Deprecation: public_metadata++<Warning>+`public_metadata` is deprecated and will be removed in Spree 6.0. Use `metadata` instead.+</Warning>++The `public_metadata` column was never exposed in Store API responses and in practice served the same purpose as `private_metadata`. It will be removed in Spree 6.0 and calling `public_metadata=` will emit a deprecation warning.++Always use the single `metadata` accessor for all schemaless key-value storage. If you need data visible to customers on the storefront, use [Metafields](/v5/developer/core-concepts/metafields) instead.++```ruby+# Deprecated — will be removed in 6.0+order.public_metadata = { 'gift_message' => 'Happy Birthday!' }++# Use metadata for internal storage+order.metadata = { 'gift_message' => 'Happy Birthday!' }++# Use metafields for customer-visible structured data+order.set_metafield('custom.gift_message', 'Happy Birthday!')+```diff --git a/docs/v5/developer/customization/model-preferences.mdx b/docs/v5/developer/customization/model-preferences.mdxnew file mode 100644index 0000000000..9a12da07da--- /dev/null+++ b/docs/v5/developer/customization/model-preferences.mdx@@ -0,0 +1,150 @@+---+title: Model Preferences+description: Add typed configuration options to Spree models using model preferences, including supported types, default values, and reading or writing stored values.+canonical: "https://spreecommerce.org/docs/developer/customization/model-preferences"+---++Model preferences allow you to easily extend Spree models with configuration options. Thanks to this you can store useful information on Spree models, eg.++```ruby+user.preferred_language = "English"+user.save+```++## Defining Model Preferences++To define a model preference, you need to add them to your model class.++Make sure to generate a migration to add the `preferences` column to the table. This column will store the preferences in a serialized format.++<CodeGroup>++```bash Spree CLI (Docker)+spree generate migration AddPreferencesToSpreeUsers preferences:text+```++```bash Without Spree CLI+bin/rails g migration AddPreferencesToSpreeUsers preferences:text+```++</CodeGroup>++Run the migration.++<CodeGroup>++```bash Spree CLI (Docker)+spree migrate+```++```bash Without Spree CLI+bin/rails db:migrate+```++</CodeGroup>++```ruby+class Spree::User < ApplicationRecord+ # ... you existing code ...++ # include the preferable module+ include Spree::Preferences::Preferable+ # define the preferences+ preference :language, :string, default: "English"+ preference :sms_marketing, :boolean, default: false+end+```++This will add a `language` preference to the `User` model. The preference will be stored in the newly created `preferences` column of the `spree_users` table. You can add more preferences to the model in the same way.++## Accessing Model Preferences++Once preferences have been defined for a model, they can be accessed either using the shortcut methods that are generated for each preference or the generic methods that are not specific to a particular preference.++### Shortcut Methods++There are several shortcut methods that are generated. They are shown below.++Query methods:++```ruby+user.prefers_sms_marketing? # => false+```++Reader methods:++```ruby+user.preferred_sms_marketing # => false+user.preferred_language # => "English"+```++Writer methods:++```ruby+user.prefers_sms_marketing = false # => false+user.preferred_language = "English" # => "English"+```++<Note>+ Remember to run `user.save` after setting the preference value to save the changes to the database.+</Note>++Check if a preference is available:++```ruby+user.has_preference? :sms_marketing+```++### Generic Methods++Each shortcut method is essentially a wrapper for the various generic methods shown below:++Query method:++```ruby+user.prefers?(:sms_marketing) # => false+user.prefers?(:language) # => false+```++Reader methods:++```ruby+user.preferred(:sms_marketing) # => false+user.preferred(:language) # => "English"+```++```ruby+user.get_preference :sms_marketing+user.get_preference :language+```++Writer method:++```ruby+user.set_preference(:sms_marketing, false) # => false+user.set_preference(:language, "English") # => "English"+```++### Accessing All Preferences++You can get a hash of all stored preferences by accessing the `preferences` helper:++```ruby+user.preferences # => {"language"=>"English", "sms_marketing"=>false}+```++This hash will contain the value for every preference that has been defined for the model instance, whether the value is the default or one that has been previously stored.++## Models with preferences++The following Spree models already have preferences defined:++* `Spree::Calculator`+* `Spree::Gateway`+* `Spree::PageBlock`+* `Spree::PageSection`+* `Spree::Page`+* `Spree::PaymentMethod`+* `Spree::PromotionRule`+* `Spree::Store`+* `Spree::Theme`\ No newline at end of filediff --git a/docs/v5/developer/customization/permissions.mdx b/docs/v5/developer/customization/permissions.mdxnew file mode 100644index 0000000000..9cdfbb44bd--- /dev/null+++ b/docs/v5/developer/customization/permissions.mdx@@ -0,0 +1,268 @@+---+title: Permissions+canonical: "https://spreecommerce.org/docs/developer/customization/permissions"+---++Spree uses [CanCanCan](https://github.com/CanCanCommunity/cancancan) for authorization. The permission system allows you to define granular access control for different user roles.++## Permission Sets (Recommended)++Permission Sets provide a clean, modular way to manage permissions. Each permission set is a reusable group of permissions that can be assigned to roles.++### How It Works++1. **Roles** - Determine which permission sets govern a user's access (e.g., `admin`, `customer_service`)+2. **Permission Sets** - Contain the logic defining what actions users can perform on resources+3. **Role Configuration** - Associates roles with their corresponding permission sets++### Configuring Roles++In your `config/initializers/spree.rb`, configure which permission sets are assigned to each role:++```ruby+Rails.application.config.after_initialize do+ # Default permissions for all users (guests and logged-in customers)+ Spree.permissions.assign(:default, [Spree::PermissionSets::DefaultCustomer])++ # Full admin access+ Spree.permissions.assign(:admin, [Spree::PermissionSets::SuperUser])++ # Custom role with specific permissions+ Spree.permissions.assign(:customer_service, [+ Spree::PermissionSets::DashboardDisplay,+ Spree::PermissionSets::OrderManagement,+ Spree::PermissionSets::UserDisplay+ ])++ # Merchandiser role for product management+ Spree.permissions.assign(:merchandiser, [+ Spree::PermissionSets::DashboardDisplay,+ Spree::PermissionSets::ProductManagement,+ Spree::PermissionSets::StockManagement+ ])+end+```++### Built-in Permission Sets++| Permission Set | Description |+|---------------|-------------|+| `SuperUser` | Full admin access with safety restrictions |+| `DefaultCustomer` | Basic storefront permissions (browse, checkout, manage own account) |+| `DashboardDisplay` | View admin dashboard |+| `OrderDisplay` | Read-only access to orders |+| `OrderManagement` | Full order management (view, edit, refund, etc.) |+| `ProductDisplay` | Read-only access to products and catalog |+| `ProductManagement` | Full catalog management (products, variants, taxonomies) |+| `UserDisplay` | Read-only access to users |+| `UserManagement` | Full user management |+| `StockDisplay` | Read-only access to inventory |+| `StockManagement` | Full inventory management |+| `PromotionManagement` | Manage promotions and coupon codes |+| `ConfigurationManagement` | Manage store settings, shipping, taxes, etc. |+| `RoleManagement` | Manage roles (except the protected admin role) |++### Creating Custom Permission Sets++Create a new permission set in `app/models/spree/permission_sets/`:++```ruby+# app/models/spree/permission_sets/warehouse_management.rb+module Spree+ module PermissionSets+ class WarehouseManagement < Base+ def activate!+ can :manage, Spree::StockItem+ can :manage, Spree::StockLocation+ can :manage, Spree::StockMovement+ can :manage, Spree::Shipment+ can [:read, :admin], Spree::Order+ end+ end+ end+end+```++Then assign it to a role:++```ruby+Spree.permissions.assign(:warehouse_staff, [+ Spree::PermissionSets::DashboardDisplay,+ Spree::PermissionSets::WarehouseManagement+])+```++### Permission Set API++Within a permission set, you have access to:++- `can(action, subject, conditions = {})` - Grant permission+- `cannot(action, subject, conditions = {})` - Deny permission+- `can?(action, subject)` - Check if permission exists+- `user` - The current user+- `store` - The current store (for multi-store setups)++```ruby+module Spree+ module PermissionSets+ class OrderManagementForOwnOrders < Base+ def activate!+ # Users can only manage orders they created+ can :manage, Spree::Order, created_by_id: user.id++ # But cannot cancel any order+ cannot :cancel, Spree::Order++ # Unless it's cancellable+ can :cancel, Spree::Order, &:allow_cancel?+ end+ end+ end+end+```++### Managing Permission Configuration++```ruby+# Assign permission sets to a role+Spree.permissions.assign(:customer_service, [+ Spree::PermissionSets::OrderDisplay,+ Spree::PermissionSets::UserManagement+])++# Add more permission sets to an existing role+Spree.permissions.assign(:customer_service, [+ Spree::PermissionSets::StockDisplay+])++# Clear all permission sets from a role+Spree.permissions.clear(:customer_service)++# Check what permission sets a role has+Spree.permissions.permission_sets_for(:customer_service)+# => [Spree::PermissionSets::OrderDisplay, ...]++# Check if a role is configured+Spree.permissions.role_configured?(:customer_service)+# => true+```++## Users and Roles++Spree comes with an `admin` role by default. You can create more roles in the Admin Panel or via Rails console:++```ruby+Spree::Role.find_or_create_by(name: 'customer_service')+Spree::Role.find_or_create_by(name: 'merchandiser')+Spree::Role.find_or_create_by(name: 'warehouse_staff')+```++Assign a role to a user:++```ruby+user = Spree.user_class.find_by(email: '[email protected]')+role = Spree::Role.find_by(name: 'customer_service')+user.spree_roles << role+```++### Default Role Behavior++- Users with **no roles assigned** automatically get the `:default` role permissions+- No `RoleUser` records are created for regular customers+- Only users with special permissions need explicit role assignments++## Legacy Approach: Custom Ability Classes++<Note>+The permission sets approach above is recommended for new projects. The legacy approach below is supported for backward compatibility.+</Note>++### Adding Custom Permissions via Decorator++Create a new ability class in `app/models/customer_service_ability.rb`:++```ruby+class CustomerServiceAbility+ include CanCan::Ability++ def initialize(user)+ if user.respond_to?(:has_spree_role?) && user.has_spree_role?('customer_service')+ can :manage, Spree::Order+ end+ end+end+```++Register it via a decorator in `app/models/spree/ability_decorator.rb`:++```ruby+module Spree+ module AbilityDecorator+ def abilities_to_register+ [CustomerServiceAbility]+ end+ end++ Ability.prepend(AbilityDecorator)+end+```++### Replacing the Ability Class++You can replace the entire ability class via [Dependencies](/v5/developer/customization/dependencies):++```ruby+# config/initializers/spree.rb+Spree::Dependencies.ability_class = 'CustomAbility'+```++```ruby+# app/models/custom_ability.rb+class CustomAbility < Spree::Ability+ def initialize(user, options = {})+ alias_cancan_delete_action++ @user = user || Spree.user_class.new+ @store = options[:store] || Spree::Current.store++ if @user.respond_to?(:has_spree_role?) && @user.has_spree_role?('admin')+ apply_admin_permissions(@user, options)+ elsif @user.respond_to?(:has_spree_role?) && @user.has_spree_role?(:customer_service)+ apply_customer_service_permissions(@user)+ else+ apply_user_permissions(@user, options)+ end++ protect_admin_role+ end++ protected++ def apply_customer_service_permissions(user)+ can :manage, Spree::Order+ can [:read, :admin], Spree.user_class+ end+end+```++## CanCanCan Reference++Spree's permission system is built on CanCanCan. Key concepts:++- `can :action, Subject` - Grant permission+- `can :manage, Subject` - Grant all actions (create, read, update, destroy)+- `cannot :action, Subject` - Explicitly deny permission+- `can :action, Subject, conditions` - Conditional permission++```ruby+# Examples+can :read, Spree::Product # Can read any product+can :manage, Spree::Order, user_id: user.id # Can manage own orders+can :update, Spree::Order do |order| # Block conditions+ order.user == user && !order.completed?+end+cannot :destroy, Spree::Order # Cannot destroy any order+can :destroy, Spree::Order, &:can_be_deleted? # Unless it's deletable+```++See the [CanCanCan documentation](https://github.com/CanCanCommunity/cancancan) for more details.diff --git a/docs/v5/developer/customization/quickstart.mdx b/docs/v5/developer/customization/quickstart.mdxnew file mode 100644index 0000000000..906b03ba5f--- /dev/null+++ b/docs/v5/developer/customization/quickstart.mdx@@ -0,0 +1,201 @@+---+title: Quickstart+og:title: Spree Customization Quickstart+description: Recommended ways to customize Spree — store settings, configuration, events, webhooks, dependencies, admin extensions, and decorators as a last resort.+canonical: "https://spreecommerce.org/docs/developer/customization/quickstart"+---++Spree is a flexible platform allowing you to customize every part of it to suit your business needs. This guide presents customization options **in order of recommendation** - start from the top and only move down if simpler options don't meet your needs.++## Quick Reference++| What you want to do | Recommended approach |+|---------------------|---------------------|+| Change store settings (currency, zones, languages) | [Store Settings](#store-settings) |+| Tweak Spree behavior globally | [Configuration](#configuration) |+| React to model changes (sync, notifications) | [Events & Subscribers](#events-and-subscribers) |+| Notify external services | [Webhooks](#webhooks) |+| Swap core services (cart, checkout, etc.) | [Dependencies](#dependencies) |+| Add admin menu items | [Admin Navigation](#admin-extensions) |+| Add sections to admin forms | [Admin Partials](#admin-extensions) |+| Add searchable/filterable fields | [Ransack Configuration](#search-and-filtering) |+| Add associations/validations to models | [Decorators](#decorators) (last resort) |++<AccordionGroup>+ <Accordion title="Store settings" defaultOpen>+ **Best for:** Changing currency, shipping zones, languages, and other business settings.++ There's a lot of Store settings you can change in the admin panel without touching the code.++ Go to **Admin > Settings**++ <img src="/images/spree_admin_store_settings.png" alt="Spree Admin Store Settings" />+ </Accordion>++ <Accordion title="Configuration">+ **Best for:** Tweaking Spree's behavior globally without modifying source code.++ Global application configuration allows you to customize various aspects of Spree:++ ```ruby config/initializers/spree.rb+ Spree.config do |config|+ config.allow_guest_checkout = false+ config.products_per_page = 20+ end+ ```++ Please see [Configuration](/v5/developer/customization/configuration) section for more information.+ </Accordion>++ <Accordion title="Events and Subscribers">+ **Best for:** Reacting to model changes, syncing with external services, sending notifications, audit logging.++ <Info>+ Events are the **recommended way** to add behavior when something happens in Spree, replacing the need for decorator callbacks.+ </Info>++ Spree's event system lets you subscribe to events like `order.completed`, `product.updated`, `payment.paid`, etc.:++ ```ruby app/subscribers/order_completed_subscriber.rb+ class OrderCompletedSubscriber < Spree::Subscriber+ subscribes_to 'order.completed'++ def handle(event)+ order = Spree::Order.find_by_prefix_id(event.payload['id'])+ return unless order++ # Sync to external service, send notification, etc.+ ExternalService.notify_order_placed(order)+ end+ end+ ```++ **Key benefits:**+ - Loose coupling - your code doesn't depend on Spree internals+ - Async by default - keeps requests fast+ - Easier testing and upgrades++ Please see [Events](/v5/developer/core-concepts/events) section for more information.+ </Accordion>++ <Accordion title="Webhooks">+ **Best for:** Notifying external services (ERPs, CRMs, fulfillment systems) when events occur.++ Webhooks send HTTP POST requests to external URLs when Spree events happen:++ - Order completed → Notify fulfillment system+ - Product updated → Sync with PIM+ - Customer created → Add to CRM++ Configure webhooks in **Admin > Developers > Webhooks** or via the API.++ Please see [Webhooks](/v5/developer/core-concepts/webhooks) section for more information.+ </Accordion>++ <Accordion title="Dependencies">+ **Best for:** Swapping core services, serializers, and abilities with your own implementations.++ Spree allows you to replace core classes without modifying them:++ ```ruby config/initializers/spree.rb+ Spree::Dependencies.cart_add_item_service = "MyCartAddItemService"+ Spree::Dependencies.cart_remove_item_service = "MyCartRemoveItemService"+ ```++ This is cleaner than decorating services because you provide a complete replacement rather than patching behavior.++ Please see [Dependencies](dependencies) section for more information.+ </Accordion>++ <Accordion title="Admin Extensions">+ **Best for:** Adding menu items, form sections, dashboard widgets, and other UI elements to the admin panel.++ Spree provides declarative APIs for extending the admin without decorators or view overrides:++ **Navigation API** - Add menu items:+ ```ruby config/initializers/spree.rb+ Rails.application.config.after_initialize do+ Spree.admin.navigation.sidebar.add :brands,+ label: :brands,+ url: :admin_brands_path,+ icon: 'award',+ position: 35+ end+ ```++ **Partials API** - Add sections to forms:+ ```ruby config/initializers/spree.rb+ Spree.admin.partials.product_form << 'spree/admin/products/erp_section'+ ```++ Please see:+ - [Admin Navigation](/v5/developer/admin/navigation) - For adding menu items+ - [Admin Partials](/v5/developer/admin/extending-ui) - For extending UI+ - [Admin Tables](/v5/developer/admin/tables) - For customizing list views+ </Accordion>++ <Accordion title="Search and Filtering">+ **Best for:** Making custom fields searchable/sortable in the admin and API.++ Instead of decorating models to add `ransackable_attributes`, use the Ransack configuration API:++ ```ruby config/initializers/spree.rb+ Spree.ransack.add_attribute :product, :erp_id+ Spree.ransack.add_association :product, :brand+ ```++ Please see [Search & Filtering](/v5/developer/core-concepts/search-filtering#extending-ransackable-configuration) section for more information.+ </Accordion>++ <Accordion title="Authentication">+ **Best for:** Using your own user model or authentication system.++ Spree allows you to use your own authentication system instead of the default Devise-based one.++ You can find more information in the [Authentication](authentication) section.+ </Accordion>++ <Accordion title="Checkout flow">+ **Best for:** Customizing checkout steps and flow.++ With Spree you can change the checkout flow to fit your business needs - add steps, remove steps, or change the order.++ Please see [Checkout flow customization section](checkout) for more information.+ </Accordion>++ <Accordion title="Decorators">+ **Best for:** Adding associations, validations, scopes, and methods to Spree models. Use as a last resort.++ <Warning>+ Decorators should be used **only when no other option works**. They tightly couple your code to Spree internals and can break during upgrades.++ **Do NOT use decorators for:**+ - After-save callbacks → Use [Events](/v5/developer/core-concepts/events) instead+ - External service sync → Use [Webhooks](/v5/developer/core-concepts/webhooks) instead+ - Custom service logic → Use [Dependencies](dependencies) instead+ - Admin UI changes → Use [Admin Extensions](#admin-extensions) instead+ </Warning>++ Decorators are still appropriate for structural changes:++ ```ruby app/models/spree/product_decorator.rb+ module Spree+ module ProductDecorator+ def self.prepended(base)+ base.belongs_to :brand, class_name: 'MyApp::Brand', optional: true+ base.validates :external_id, presence: true+ base.scope :featured, -> { where(featured: true) }+ end++ def full_title+ "#{brand&.name} #{name}"+ end+ end++ Product.prepend(ProductDecorator)+ end+ ```++ Please see [Decorators](decorators) section for more information.+ </Accordion>+</AccordionGroup>diff --git a/docs/developer/customization/routes.mdx b/docs/v5/developer/customization/routes.mdxsimilarity index 90%rename from docs/developer/customization/routes.mdxrename to docs/v5/developer/customization/routes.mdxindex 49ae9a8355..51c2248249 100644--- a/docs/developer/customization/routes.mdx+++ b/docs/v5/developer/customization/routes.mdx@@ -1,6 +1,7 @@---title: Routesdescription: Learn how to customize the routes in Spree+canonical: "https://spreecommerce.org/docs/v5/developer/customization/routes"---## Default configurationdiff --git a/docs/v5/developer/customization/validations.mdx b/docs/v5/developer/customization/validations.mdxnew file mode 100644index 0000000000..27a2725282--- /dev/null+++ b/docs/v5/developer/customization/validations.mdx@@ -0,0 +1,174 @@+---+title: Validations+section: customization+canonical: "https://spreecommerce.org/docs/developer/customization/validations"+---++## 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](/v5/developer/customization/workflows) |+| The **shape of a record** — a field you added must be present, a format must match | A [decorator](/v5/developer/customization/decorators) adding a validation |+| A **new attribute** you need on an existing model | [Custom fields](/v5/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](/v5/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](/v5/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](/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/v5/developer/customization/workflows.mdx b/docs/v5/developer/customization/workflows.mdxnew file mode 100644index 0000000000..ccceb5f618--- /dev/null+++ b/docs/v5/developer/customization/workflows.mdx@@ -0,0 +1,527 @@+---+title: Services & Workflows+section: customization+canonical: "https://spreecommerce.org/docs/developer/customization/workflows"+---++## Overview++Spree's business logic lives in two kinds of plain Ruby classes. Both are called+the same way and both return the same result object, so as a caller you never+need to know which one you're using.++**Services** (`app/services/`) are the default. A service is an ordinary class+with a `call` method — creating a customer, updating a price, removing an item+from a cart. Most of Spree is services.++**Workflows** (`app/workflows/`) handle the flows that need more: completing a+checkout, cancelling an order, capturing a payment, creating a fulfillment.+These are the operations where something can go wrong halfway through, where+money moves, or where you might want to inject your own logic partway.++A workflow earns its place by needing at least one of:++* **Extension points** — named places where your code can run inside the flow+* **External calls** — payment gateways, carrier APIs, anything over the network+* **Compensation** — undoing earlier work when a later step fails++Everything else stays a service. If you're writing a plain create-update-delete+operation, write a service.++## Calling them++Identical for both:++```ruby+result = Spree.cart_add_item_workflow.call(cart: cart, variant: variant, quantity: 2)++if result.success?+ line_item = result.value+else+ puts result.error.to_s+end+```++Never raise on expected failures — check `result.success?`. See+[Dependencies](/v5/developer/customization/dependencies) for how to swap either one+for your own class.++## Extending a workflow with hooks++Before hooks, customizing a flow meant replacing the whole class and keeping+your copy in sync with every Spree release. Hooks let you run your own code at a+named point inside a flow you don't own.++Register in `config/initializers/spree.rb`:++```ruby+Spree.hooks.register('carts.add_item.validate', 'MyStore::CheckPurchaseLimit')+```++The key is `<workflow>.<hook>`. Handlers are stored as **class name strings**,+resolved when the hook fires — that keeps registration safe at boot time and+survives code reloading in development. A block works for one-liners:++```ruby+Spree.hooks.register('orders.cancel.after_cancel') do |workflow|+ MyStore::Analytics.track(:order_cancelled, workflow.order.number)+end+```++Your handler is a class with a `call` method that receives the workflow:++```ruby+module MyStore+ class CheckPurchaseLimit+ def call(workflow)+ # every #perform keyword is a reader: cart, variant, quantity, ...+ 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+```++`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+workflow, so a typo fails immediately instead of silently never firing.+</Note>++## Every hook can have many handlers++A hook is not a single slot. Your extension, another extension and the host+application can all register against the same key, and every one of them runs.+Assume you are never alone on a hook.++```ruby+Spree.hooks.register('carts.add_item.validate', 'MyStore::CheckPurchaseLimit')+Spree.hooks.register('carts.add_item.validate', 'OtherGem::CheckChannelRules')+Spree.hooks.register('carts.add_item.validate') { |workflow| ... }+# all three run+```++**Handlers run in registration order** — the order the `register` calls+happened, which for gems is initializer load order. Don't depend on it. If your+handler only makes sense after another one has run, you have a sequencing+requirement that hooks don't express; put both pieces in one handler.++**Registering the same class twice is a no-op.** `register` deduplicates by+class name, so an initializer that runs twice (or a gem registering defensively)+won't double up. Two *different* classes are two handlers, and two separate+blocks are always two handlers — blocks can't be compared, so prefer class names+anywhere registration might repeat.++What "many handlers" means differs by kind:++| Kind | With several handlers |+|---|---|+| `validate` | Runs in order until one rejects. **The first `reject!` stops the flow** — later validate handlers never run, so don't rely on yours executing. |+| Context | **All** run and their hashes are merged. A key set by two handlers goes to the last one registered, and the collision is reported through `Rails.error`. |+| Lifecycle | All run in order. Return values are ignored. |++One consequence worth planning for: because any handler can veto, a `validate`+handler should say *why* it rejected in the message, and a lifecycle handler+should not assume it is the only observer of the event.++<Warning>+Handlers are not isolated from each other. An exception raised in one propagates+out of the workflow, later handlers on that hook never run, and an open+transaction rolls back — a `raise` in an `after_item_added` handler leaves the+customer's item not added at all.++If your handler does something optional (analytics, a nice-to-have+notification), rescue inside it so a failure in your code can't undo someone+else's order. Work that is genuinely allowed to fail belongs in an+[event subscriber](/v5/developer/core-concepts/events), not a hook.+</Warning>++## The three kinds of hooks++### Lifecycle hooks — react to something that happened++Named in the past tense (`after_item_added`, `after_cancel`, `after_create`).+They run after the work is done. Return values are ignored; you cannot change+the outcome.++```ruby+class MyStore::NotifyWarehouse+ def call(workflow)+ WarehouseApi.notify(workflow.fulfillment.number)+ end+end++Spree.hooks.register('fulfillments.create.after_create', 'MyStore::NotifyWarehouse')+```++Note that some lifecycle hooks run **inside** the flow's database transaction+(`after_item_added`, `after_cancel`). That's deliberate — it lets you write+related records atomically with the change. It also means slow work does not+belong there: use an [event subscriber](/v5/developer/core-concepts/events) for+emails, webhooks and other eventual work.++### Validation hooks — veto before the work happens++Always called `validate`. They run **before** anything is written, so rejecting+costs nothing — no rollback, no partial state, no money moved.++Call `reject!` on the workflow to stop the flow:++```ruby+module MyStore+ class LimitReturnWindow+ def call(workflow)+ return if workflow.order.completed_at > 30.days.ago++ workflow.reject!('This order is outside the 30-day return window.')+ end+ end+end+```++The caller receives a normal failure result — no exception reaches your+controller:++```ruby+result = Spree.return_create_workflow.call(order: order, items: items)+result.success? # => false+result.error.to_s # => "This order is outside the 30-day return window."+result.error.value # => ActiveModel::Errors — the rejection, field by field+```++<Warning>+Reject from `validate` hooks, not from `after_*` hooks. Rejecting late still+rolls the database back, but it cannot undo work that already left the system —+`carts.complete.before_finalize` runs *after* the customer's card was charged,+so rejecting there rolls back the order while the charge stands. If you need to+stop a flow, `validate` is the place.+</Warning>++### Context hooks — feed data into a calculation++Named imperatively (`set_promotion_context`, `set_tax_line_context`,+`get_provider_data`). They run before a calculation so you can contribute data+to it.++Your handler **returns a hash**. Spree merges the hashes from every registered+handler and hands the result to the workflow:++```ruby+module MyStore+ class TaxExemption+ def call(workflow)+ certificate = workflow.cart.customer&.tax_exemption_certificate+ return {} if certificate.blank?++ { exemption_certificate: certificate.number }+ end+ end+end++Spree.hooks.register('carts.recalculate_totals.set_tax_line_context', 'MyStore::TaxExemption')+```++Handlers stay independent — there is no shared object to mutate and no ordering+to reason about. A handler returning anything other than a hash contributes+nothing, so lifecycle-style handlers are harmless if registered here by mistake.++If two handlers set the same key, the last registered one wins and the collision+is reported through `Rails.error` so it's visible rather than mysterious.++## Available hooks++| Workflow key | Hook | Kind | When it runs |+|---|---|---|---|+| `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, immediately before that item is applied — quantity edits, removals and bulk payloads. Earlier items in the batch may already be written |+| `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 |+| `carts.merge` | `validate` | validate | Before any items move between carts |+| `carts.merge` | `after_merge` | lifecycle | After the carts are folded together |+| `carts.recalculate` | `set_promotion_context` | context | Before promotions are evaluated |+| `carts.recalculate` | `after_recalculate` | lifecycle | After the cart is fully repriced |+| `carts.recalculate_totals` | `set_tax_line_context` | context | Before tax is estimated |+| `orders.cancel` | `before_cancel` | validate | Before the cancellation is recorded |+| `orders.cancel` | `after_cancel` | lifecycle | With the cancellation, in transaction |+| `orders.resume` | `before_resume` | validate | Before the order is un-cancelled |+| `orders.resume` | `after_resume` | lifecycle | With the status flip, in transaction |+| `fulfillments.create` | `validate` | validate | Before the order is locked |+| `fulfillments.create` | `get_provider_data` | context | Before the fulfillment is built |+| `fulfillments.create` | `after_create` | lifecycle | After the fulfillment is created and totals recalculated |+| `payments.capture` | `validate` | validate | Before the gateway is called |+| `payments.capture` | `before_capture` | lifecycle | Immediately before the gateway call |+| `payments.capture` | `after_capture` | lifecycle | After a successful capture |+| `payments.refund` | `validate` | validate | Before the refund record exists |+| `payments.refund` | `before_refund` | lifecycle | Immediately before the gateway call |+| `payments.refund` | `after_refund` | lifecycle | After a successful refund |+| `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) |+| `products.activate` | `validate` | validate | Before the product goes on sale — the place to require an image, a price or a category |+| `products.activate` | `after_activate` | lifecycle | After the status is written (in transaction) |+| `products.archive` | `validate` | validate | Before the product is taken off sale |+| `products.archive` | `after_archive` | lifecycle | After the status is written (in transaction) |+| `products.draft` | `validate` | validate | Before the product returns to draft |+| `products.draft` | `after_draft` | lifecycle | After the status is written (in transaction) |+| `gift_cards.apply` | `validate` | validate | Before a card is drawn against — who may spend a card, on what, up to how much |+| `gift_cards.apply` | `after_apply` | lifecycle | After the store credit and payment exist (in transaction) |+| `gift_cards.remove` | `validate` | validate | Before a card is taken back off an order |+| `gift_cards.remove` | `after_remove` | lifecycle | After the balance is returned to the card (in transaction) |+| `gift_cards.redeem` | `validate` | validate | Before the card is recorded as spent |+| `gift_cards.redeem` | `after_redeem` | lifecycle | After the status is written (in transaction) |+| `gift_cards.cancel` | `validate` | validate | Before a card is voided |+| `gift_cards.cancel` | `after_cancel` | lifecycle | After the card is voided (in transaction) |+| `price_lists.create` | `validate` | validate | After the list is built, before it is saved |+| `price_lists.create` | `after_create` | lifecycle | After the list and its product membership exist (in transaction) |+| `price_lists.update` | `validate` | validate | With the pending attributes assigned, before anything is written |+| `price_lists.update` | `after_update` | lifecycle | After membership and price overrides are applied (in transaction) |+| `price_lists.activate` | `validate` | validate | Before a price list takes effect |+| `price_lists.activate` | `after_activate` | lifecycle | After the list goes live or is scheduled (in transaction) |+| `price_lists.deactivate` | `validate` | validate | Before a price list stops applying |+| `price_lists.deactivate` | `after_deactivate` | lifecycle | After the list is switched off (in transaction) |+| `invitations.accept` | `validate` | validate | After the expiry and invitee checks pass, before any access is granted |+| `invitations.accept` | `after_accept` | lifecycle | After the role is granted and the invitation marked accepted (in transaction) |+| `imports.start_mapping` | `validate` | validate | Before the uploaded file is read |+| `imports.start_mapping` | `after_start_mapping` | lifecycle | After the column mappings are built (in transaction) |+| `imports.complete_mapping` | `validate` | validate | Before the mapping is accepted — refuse a mapping your store considers incomplete |+| `imports.complete_mapping` | `after_complete_mapping` | lifecycle | After the mapping is accepted, before row creation is dispatched (in transaction) |+| `imports.start_processing` | `validate` | validate | Before the import starts working through its rows |+| `imports.start_processing` | `after_start_processing` | lifecycle | After the status is written (in transaction) |+| `imports.complete` | `validate` | validate | Before the import is closed out |+| `imports.complete` | `after_complete` | lifecycle | After the import is completed and the store touched (in transaction) |+| `imports.retry_failed_rows` | `validate` | validate | Before failed rows are queued again |+| `imports.retry_failed_rows` | `after_retry` | lifecycle | After the import returns to processing, before re-dispatch (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.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:++```ruby+Spree.hooks.workflows # => { 'carts.add_item' => 'Spree::Carts::AddItem', ... }+Spree::Carts::Complete.declared_hooks # => [:validate, :before_finalize, :after_finalize]+Spree.hooks.keys # => registered keys+Spree.hooks.validate! # => true, or raises on a bad registration+```++## Writing your own workflow++Most extensions only need hooks. Write a workflow when you're adding a *new*+multi-step operation of your own — one with external calls, compensation, or+extension points for others.++```ruby+module MyStore+ class Subscriptions::Renew < Spree::Workflow+ hooks :validate, :after_renew++ attr_reader :order++ # The method signature is the contract — Ruby raises on a missing or+ # unknown keyword, and a bare `super` turns each parameter into a reader.+ #+ # @param subscription [MyStore::Subscription]+ # @param renewed_at [Time, nil]+ def perform(subscription:, renewed_at: nil)+ super++ step :ensure_renewable+ run_hooks :validate++ ApplicationRecord.transaction do+ step :build_order, on_flow_failure: :discard_order+ step :extend_period+ end++ external_step :charge_customer++ run_hooks :after_renew+ subscription.publish_event('subscription.renewed')+ success(order)+ end++ private++ def ensure_renewable+ failure(subscription, :not_active) unless subscription.active?+ end++ def build_order+ @order = MyStore::Subscriptions::BuildOrder.call(subscription: subscription).value+ end++ def extend_period+ subscription.update!(renews_at: (renewed_at || Time.current) + 1.month)+ end++ def charge_customer+ Spree.payment_capture_workflow.call(payment: order.payments.last)+ end++ # Runs if a later step fails after the transaction committed.+ def discard_order+ order&.destroy+ end+ end+end+```++The whole vocabulary:++| | |+|---|---|+| `step :name` | Runs the private method of that name |+| `external_step :name` | Same, but refuses to run inside a database transaction this workflow opened — use it for every network call |+| `with: -> { ... }` | Delegates a step to a swappable collaborator, keyword arguments sliced from the workflow's readers |+| `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!` | 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 |++Everything else is ordinary Rails — `ApplicationRecord.transaction`,+`with_lock`, `if`, `rescue`, `publish_event`.++Two rules worth internalising:++**Network calls never share a database transaction.** That's what+`external_step` enforces. A gateway call inside a transaction holds a database+connection open across a network round trip, and a timeout leaves your database+and the payment processor disagreeing about what happened.++**Models get a plain `status` string, not a state machine.** Transitions are+workflows: `MyStore::Subscriptions::Cancel.call(...)`, not `subscription.cancel!`.+Transition callbacks hide side effects inside a save, cannot take arguments, and+have no compensation story.++As of 6.0 this is not just advice for new models — Spree has no state machines+left. Every status a record can hold is declared with `Spree::HasStatus`, and+every move between two of them is a workflow you can hook.++## Statuses++`Spree::HasStatus` declares the statuses a model can hold:++```ruby+class MyStore::Subscription < Spree.base_class+ include Spree::HasStatus+ has_status :trialing, :active, :paused, :canceled, default: :trialing+end+```++That gives you an inclusion validation, a predicate per value+(`subscription.paused?`), a scope per value (`Subscription.paused`) and+`with_status(:active, :trialing)` for several at once. It deliberately does+*not* give you a transition graph — deciding which moves are legal is the+workflow's job, which is what lets a transition take arguments, call out to a+gateway outside a transaction, and undo itself when a later step fails.++Statuses are additive, so an extension can add its own without reopening the+model:++```ruby+Spree::GiftCard.add_status(:on_hold, after: :active)+```++A custom status needs a custom workflow to move records into it. That is the+design, not a gap: a central place validating transitions would be a state+machine again.++<Note>+`has_status` never overwrites something the model already defines. Where a+status name means more than the column value — `Spree::GiftCard#active?` also+requires the card not to have expired, and `Spree::GiftCard.active` includes+partially redeemed cards — the model's own definition wins and the generated+one is skipped.+</Note>++### Moving a record between statuses++Call the workflow, not the model:++```ruby+result = Spree.product_archive_workflow.call(product: product)+result.success?+```++Spree ships one workflow per transition — `Spree::Products::Activate`,+`Spree::GiftCards::Redeem`, `Spree::Imports::Complete`, and so on — each with+its own `validate` and `after_*` hooks, all in+[Available hooks](#available-hooks) above. Because the write and the event it+publishes happen in the same place, registering against a hook is enough to+see every transition, wherever it was triggered from.++## Observability++Every step emits an `ActiveSupport::Notifications` event, so your APM sees the+flow without extra instrumentation:++```ruby+ActiveSupport::Notifications.subscribe('step.spree_workflow') do |*, payload|+ Rails.logger.info("#{payload[:workflow]}##{payload[:step]}")+end+```++## Choosing an extension point++| You want to | Use |+|---|---|+| Stop an operation from happening | A `validate` hook |+| Add data to a pricing or tax calculation | A context hook |+| Do something after an operation, in the same transaction | A lifecycle hook |+| Send an email, call a webhook, update a search index | An [event subscriber](/v5/developer/core-concepts/events) |+| Replace an operation entirely | [Dependencies](/v5/developer/customization/dependencies) |+| Add a brand-new multi-step operation | Your own workflow |++Reach for the smallest one that does the job. A hook survives Spree upgrades;+a replaced class has to be kept in sync with every release.diff --git a/docs/v5/developer/dashboard/concepts.mdx b/docs/v5/developer/dashboard/concepts.mdxnew file mode 100644index 0000000000..a4a67edb8c--- /dev/null+++ b/docs/v5/developer/dashboard/concepts.mdx@@ -0,0 +1,104 @@+---+title: Concepts+sidebarTitle: Concepts+description: The mental model — what the dashboard is built on, how the pieces fit together, and what you need to know about each layer before you start customizing.+canonical: "https://spreecommerce.org/docs/developer/dashboard/concepts"+---++This page is a five-minute orientation for the dashboard's technology choices and how they cooperate. If you're already familiar with React + TanStack + Tailwind, skim it for the Spree-specific bits and move on.++## Tech stack at a glance++| Layer | What we use | Why it matters |+|---|---|---|+| Build | [Vite](https://vitejs.dev/) | Fast HMR, dev server, source consumption of TS/TSX |+| UI runtime | [React 19](https://react.dev/) | Components, hooks, suspense |+| Routing | [TanStack Router](https://tanstack.com/router) (file-based) | Type-safe URLs, nested layouts, search params |+| Data | [TanStack Query v5](https://tanstack.com/query) | Caching, refetch, mutation tracking |+| Forms | [React Hook Form](https://react-hook-form.com/) + [Zod](https://zod.dev/) | Uncontrolled inputs + schema validation |+| Styling | [Tailwind v4](https://tailwindcss.com/) + [shadcn/ui](https://ui.shadcn.com/) + [Base UI](https://base-ui.com/) | Utility classes + headless primitives |+| i18n | [i18next](https://www.i18next.com/) | Translations, fallback chains |+| Lint/format | [Biome](https://biomejs.dev/) | ESLint + Prettier in one tool |+| HTTP | [`@spree/admin-sdk`](https://www.npmjs.com/package/@spree/admin-sdk) | Typed Admin API client |++The dashboard is a **Single Page Application**: one HTML page, all routing client-side. No Rails views, no Turbo, no server-rendered partials. Everything the user sees comes from React components fetching JSON from `/api/v3/admin/*`.++## The three-package split++```+@spree/dashboard-ui ─ design system: shadcn primitives + headless compounds + tokens+@spree/dashboard-core ─ framework: registries + providers + hooks + SDK client + plugin facade+@spree/dashboard ─ app shell: routes, resource hooks, locales, vite config+```++[Overview](/v5/developer/dashboard/overview) covers the split in more detail. The short version: **`-ui`** has no providers or hooks (data comes via props); **`-core`** is the extension API and runtime services; **`-dashboard`** is the deployable app shell. Plugins and customizations consume `-core` and `-ui`, never the app shell.++## How customization plugs in++Five global, in-memory registries hold the things you add or modify:++| Registry | Adds | Surfaced by |+|---|---|---|+| `nav` | Sidebar entries | `<AppSidebar>` |+| `settingsNav` | Settings sub-shell entries | `<SettingsSidebar>` |+| Route registry | Custom pages mounted under `/$storeId/*` | Catch-all dispatcher route |+| Slot registry | Components injected into named slots in built-in pages | `<Slot name="...">` |+| Table registry | Columns (and their filters) on built-in list tables | `<ResourceTable>` |++Each is a module singleton with mutators to add, remove, and patch entries (nav can also insert relative to an existing entry or nest children under one). The consumer components subscribe to changes, so registering late still updates the UI on the next render.++The facade `defineDashboardPlugin({ nav, routes, slots, … })` groups all five into one declarative call — convenient for plugins, optional for in-app customizations (you can call `nav.add()` directly).++## Auth, context, providers++The signed-in admin's identity and abilities are exposed via three providers wrapping the app:++- `<AuthProvider>` — the current admin user; `useAuth()` returns `{ user, signIn, signOut, … }`+- `<PermissionProvider>` — CanCanCan abilities; `usePermissions()` returns `{ can, cannot }`+- `<StoreProvider>` — current store + timezone + currency; `useStore()` returns `{ storeId, store, … }`++When you write a custom page or hook, pull from these. **Never reach into local state for identity** — it changes on store switch or session refresh, and the providers wire all that for you.++## Data fetching++Every screen in the dashboard follows the same pattern:++```+adminClient (SDK)+ ↓ called inside+useFoo (custom hook wrapping useQuery)+ ↓ consumed by+<FooList /> (component renders cached data, owns no fetching logic)+```++Wrap SDK calls in custom hooks under `src/hooks/`, never call `adminClient` directly from components. See [Backend integration](/v5/developer/dashboard/customization/backend) for the full pattern, error mapping, and the `useResourceMutation` helper that wires up 422 handling.++## URL = state++The dashboard treats the URL as the single source of truth for page state:++- Filters, sort, page number → URL search params+- Selected row → URL path param+- "Sheet open?" → URL search param (`?edit=prod_xxx`)++This is why links work, deep-links restore filter state, and the browser back button does the right thing. When you build a custom page, follow the same rule — don't stash filter state in React state where it's invisible to bookmarks and analytics.++## i18n is not optional++The dashboard ships with English, German, French, Polish, Arabic, and Simplified Chinese out of the box. Every label, placeholder, error message goes through `i18n.t()`. When you add a feature:++1. Add the keys to your customization's `locales/en.json`+2. Register the bundle: `i18n.addResourceBundle('en', 'translation', bundle, true, true)`+3. Use `useTranslation()` in components and `i18n.t()` at registration sites++[Translations](/v5/developer/dashboard/customization/translations) covers the field-key convention.++## Prefixed IDs everywhere++The Admin API uses [Stripe-style prefixed IDs](/api-reference/admin-api/introduction): `prod_86Rf07xd4z`, `cust_k5nR8xLq`. The dashboard does too — URLs, hook params, table rows, SDK calls. Never coerce IDs to integers. Never strip the prefix. Pass them around as opaque strings.++## Where to go next++- [Public API](/v5/developer/dashboard/public-api) — what's importable from `@spree/dashboard-core` / `-ui` / `-dashboard`+- [Customization Quickstart](/v5/developer/dashboard/customization/quickstart) — first nav entry in 30 seconds+- [Recipes](/v5/developer/dashboard/recipes/custom-form-field) — focused walkthroughs for common extension shapesdiff --git a/docs/v5/developer/dashboard/customization/backend.mdx b/docs/v5/developer/dashboard/customization/backend.mdxnew file mode 100644index 0000000000..2fa72e3bc5--- /dev/null+++ b/docs/v5/developer/dashboard/customization/backend.mdx@@ -0,0 +1,127 @@+---+title: Backend integration+sidebarTitle: Backend integration+description: Talk to your own (or Spree's) Admin API from the dashboard — typed SDK calls, custom endpoints, prefixed IDs, error handling, and React-Query hooks.+canonical: "https://spreecommerce.org/docs/developer/dashboard/customization/backend"+---++The dashboard never reaches into Rails models or fetches HTML. All data flows through `@spree/admin-sdk` — a typed Admin API client. This page covers the patterns: calling existing endpoints, adding new ones, handling errors, and wrapping it all in React-Query hooks for caching.++## The `adminClient`++The SPA boots a single `adminClient` instance and exposes it from `@spree/dashboard-core`. Resource methods follow `client.<resource>.<verb>()`:++```ts+import { adminClient } from '@spree/dashboard-core'++await adminClient.products.list({ filter: { name_cont: 'shirt' } })+await adminClient.products.get('prod_86Rf07xd4z', { expand: ['variants'] })+await adminClient.products.create({ name: 'New product' })+await adminClient.products.update('prod_86Rf07xd4z', { name: 'Renamed' })+await adminClient.products.delete('prod_86Rf07xd4z')+```++All IDs are [prefixed](/api-reference/admin-api/querying) — pass them in, get them out. The SDK never coerces to integers.++## Custom endpoints++When you've added an endpoint to `spree/api` that the SDK doesn't model yet (host-app routes, an in-development feature, a custom controller), use the public `request<T>()` escape hatch:++```ts+import type { AdminBrand } from './types'++const data = await adminClient.request<{ data: AdminBrand[] }>(+ 'GET',+ '/brands',+ { params: { 'filter[name_cont]': 'nike' } },+)+```++It accepts:++- `method` — `'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'`+- `path` — relative to `/api/v3/admin` (so `/brands` hits `/api/v3/admin/brands`)+- `body` — JSON-stringified for non-GET requests+- `params` — query string++Resource methods are just `request<T>()` calls with the right path + types pre-bound. When you publish your customization or generate types from your serializer, you can promote the inline call to a typed wrapper.++## React-Query hooks++The dashboard's data layer is React-Query — every `useFoo` hook is `useQuery({ queryKey, queryFn })` over an SDK call. Follow the same pattern for your own data:++```ts+import { adminClient } from '@spree/dashboard-core'+import { useQuery } from '@tanstack/react-query'+import type { AdminBrand } from './types'++export function useBrands(params?: { search?: string }) {+ return useQuery({+ queryKey: ['brands', params],+ queryFn: () =>+ adminClient.request<{ data: AdminBrand[] }>('GET', '/brands', { params }),+ staleTime: 30_000,+ })+}+```++For mutations, prefer the existing `useResourceMutation` helper — it wires up the SDK's error shape, the 422 silencer, and the toast for non-validation errors:++```ts+import { useResourceMutation } from '@spree/dashboard-core'++export function useUpdateBrand(id: string) {+ return useResourceMutation({+ mutationFn: (body: Partial<AdminBrand>) =>+ adminClient.request<{ data: AdminBrand }>('PATCH', `/brands/${id}`, { body }),+ invalidate: [['brands'], ['brand', id]],+ })+}+```++The `invalidate` array refetches dependent queries on success.++## Error handling++The SDK throws `SpreeError` for non-2xx responses. The error carries `status`, `code`, and `details` — the last contains the Rails error hash for 422s.++```ts+import { SpreeError } from '@spree/admin-sdk'++try {+ await adminClient.products.update(id, payload)+} catch (err) {+ if (err instanceof SpreeError && err.status === 422) {+ console.log(err.details) // { name: ["can't be blank"] }+ }+ throw err+}+```++In a React Hook Form submit handler, prefer the higher-level helper:++```tsx+import { mapSpreeErrorsToForm } from '@spree/dashboard-core'++async function handleSubmit(values: FormValues) {+ try {+ await mutation.mutateAsync(values)+ } catch (err) {+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err+ }+}+```++`mapSpreeErrorsToForm` routes flat field errors onto `aria-invalid` `<FieldError>` blocks and `:base` errors onto `errors.root.message` for a destructive banner. Returns `true` if it handled the error; otherwise re-throw so the global toast catches it.++## When to add a new endpoint++Pretty much always, for anything non-trivial. If you're filtering, sorting, or aggregating across multiple resources, do it on the backend — the API can join, scope, and serialize correctly in one round-trip, whereas the dashboard would have to fan out N requests and stitch them together. See the backend customization docs for adding controllers, serializers, and authorization.++## Reference++- [Admin API reference](/api-reference/admin-api/introduction) — auth, querying, errors, and every endpoint+- [`AdminClient.request`](https://github.com/spree/spree/blob/main/packages/admin-sdk/src/admin-client.ts) — full type+- [`SpreeError`](https://github.com/spree/spree/blob/main/packages/sdk-core/src/errors.ts)+- [`useResourceMutation`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/hooks/use-resource-mutation.ts)+- [`mapSpreeErrorsToForm`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/form-errors.ts)diff --git a/docs/v5/developer/dashboard/customization/navigation.mdx b/docs/v5/developer/dashboard/customization/navigation.mdxnew file mode 100644index 0000000000..e1095af103--- /dev/null+++ b/docs/v5/developer/dashboard/customization/navigation.mdx@@ -0,0 +1,212 @@+---+title: Navigation+sidebarTitle: Navigation+description: Add, modify, and remove items from the dashboard's main sidebar and settings sub-nav.+canonical: "https://spreecommerce.org/docs/developer/dashboard/customization/navigation"+---++The dashboard has two navigation registries: **main sidebar** (`nav`) and **settings sub-shell** (`settingsNav`). Both are module singletons exposed from `@spree/dashboard-core` and consumed by `<AppSidebar>` and `<SettingsSidebar>` via `useSyncExternalStore`, so late registration re-renders the sidebars automatically.++## Main sidebar (`nav`)++### Add an entry++```ts+import { nav } from '@spree/dashboard-core'+import { BarChartIcon } from 'lucide-react'++nav.add({+ key: 'analytics',+ label: 'Analytics',+ path: '/analytics', // prefixed with /$storeId at render time+ icon: BarChartIcon,+ position: 650,+ subject: 'Spree::Order', // optional CanCanCan subject — hides item without read permission+})+```++`position` controls ordering — built-ins use 100–600 (Home 100, Orders 200, Products 300, Customers 400, Promotions 500, Reports 600; a conditional Getting Started entry sits at 50), leaving gaps to slot into. The default is 100. Keys must be unique, including against the built-in keys (`getting-started`, `home`, `orders`, `products`, `customers`, `promotions`, `reports`, `settings`) — duplicates throw at boot.++### Add via `defineDashboardPlugin`++The facade groups multiple registry calls:++```ts+import { defineDashboardPlugin } from '@spree/dashboard-core'++defineDashboardPlugin({+ nav: [+ { key: 'analytics', label: 'Analytics', path: '/analytics', icon: BarChartIcon, position: 650 },+ { key: 'segments', label: 'Segments', path: '/segments', icon: UsersIcon, position: 660 },+ ],+})+```++### Nest children under a parent++```ts+nav.add({+ key: 'analytics',+ label: 'Analytics',+ icon: BarChartIcon,+ position: 650,+ children: [+ { key: 'analytics.sales', label: 'Sales', path: '/analytics/sales' },+ { key: 'analytics.traffic', label: 'Traffic', path: '/analytics/traffic' },+ ],+})+```++Children declare their own `subject` independently — the parent doesn't auto-gate them.++### Nest under an existing (built-in) parent++To add an item **inside** a menu you don't own — e.g. a "Brands" page under the built-in **Products** menu — use `addChild`, which preserves the parent's existing children. (`nav.update('products', { children: [...] })` would *replace* them, dropping the built-ins.)++```ts+nav.addChild('products', {+ key: 'products.brands',+ label: 'Brands',+ path: '/products/brands',+ subject: 'Spree::Brand',+})+```++Or declaratively, keyed by parent:++```ts+defineDashboardPlugin({+ nav: {+ addChildren: {+ products: [{ key: 'products.brands', label: 'Brands', path: '/products/brands' }],+ },+ },+})+```++Nesting under a missing parent throws; a duplicate child key throws (`updateChild` / `removeChild` mutate an existing one). Built-in parents (`products`, `orders`, `customers`, `promotions`) register during app bootstrap, before any plugin runs, so they're always available to nest into.++### Insert relative to an existing entry++```ts+nav.insertBefore('customers', { key: 'segments', label: 'Segments', path: '/segments' })+nav.insertAfter('orders', { key: 'returns', label: 'Returns', path: '/returns' })+```++The new entry inherits the target's `position` ± 1 unless you specify your own.++### Modify or remove++Imperatively:++```ts+nav.update('orders', { label: 'All orders' })+nav.remove('legacy-thing')+```++Or declaratively in `defineDashboardPlugin` — the `nav` object form adds, removes, and patches in one config (built-in entries included; they register before any plugin runs):++```ts+defineDashboardPlugin({+ nav: {+ add: [{ key: 'reviews', label: 'Reviews', path: '/reviews', position: 650 }],+ remove: ['promotions'],+ update: { products: { label: 'Catalog', position: 150 } },+ },+})+```++The array form (`nav: [...]`) remains the shorthand for `{ add: [...] }`. The object form also takes `addChildren` (see [Nest under an existing parent](#nest-under-an-existing-built-in-parent)). `remove` of an unknown key is a no-op; `update` of an unknown key throws. `settingsNav` accepts the same object form (minus `addChildren` — settings entries are flat).++### Bottom-pinned entries++`section: 'bottom'` pins to the sidebar footer (where "Settings" lives by default):++```ts+nav.add({+ key: 'help',+ label: 'Help',+ path: '/help',+ icon: HelpCircleIcon,+ section: 'bottom',+})+```++### Conditional visibility and badges++Beyond permission gating with `subject`, a top-level entry can hide itself based on app state (`if`) and render a component after its label (`badge`):++```tsx+nav.add({+ key: 'onboarding',+ label: 'Onboarding',+ path: '/onboarding',+ // Receives the current store/user/permissions; return false to hide.+ if: ({ store }) => !storeFullyConfigured(store),+ // A component, not an element — it can call hooks and return null.+ badge: PendingTasksBadge,+})+```++The built-in Getting Started entry works exactly this way: it shows a remaining-tasks count and disappears once every setup task is done. `if` combines with `subject` — both must pass.++## Settings sub-nav (`settingsNav`)++The settings page has its own sub-shell sidebar with grouped entries (Store, Localization, Team & Access, …). Entries cluster under groups defined separately.++### Register a group++```ts+import { settingsNav } from '@spree/dashboard-core'++settingsNav.addGroup({+ key: 'integrations',+ label: 'Integrations',+ position: 500,+})+```++### Add entries to a group++```ts+settingsNav.add({+ key: 'stripe-tax',+ label: 'Stripe Tax',+ path: '/integrations/stripe-tax', // prefixed with /$storeId/settings+ group: 'integrations',+ position: 100,+ subject: 'Spree::TaxRate',+})+```++### `comingSoon` badge++Disabled entries with a "Soon" badge — useful for staging the rollout:++```ts+settingsNav.add({+ key: 'reports',+ label: 'Reports',+ path: '/reports',+ group: 'analytics',+ comingSoon: true,+})+```++## Permission gating++`subject` on a nav entry checks `permissions.can('read', subject)` — when it fails, the sidebar item is hidden. **This is UX, not authorization.** The backend still enforces CanCanCan via `authorize!` on every API call. Hiding the link is a hint, not a security boundary.++## Order of operations++Nav registrations run at module-load time. The sidebar reads via `useSyncExternalStore`, so:++- Registering before the sidebar mounts: works (the snapshot picks it up on first render)+- Registering after the sidebar mounts: also works (the store notifies subscribers)++The only ordering rule is **i18n**: if you use `i18n.t('admin.foo.label')` for `label`, your translation bundle must be registered first. The framework's own translations load before `src/plugins.ts` runs, so the rule reduces to: put your `i18n.addResourceBundle(...)` call at the top of `plugins.ts`, above the registrations that use it. See [Translations](/v5/developer/dashboard/customization/translations).++## Reference++- [`NavEntry`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/nav-registry.ts) — the full shape including types for `children`, `position`, `subject`, `section`+- [`SettingsNavEntry`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/settings-nav-registry.ts) — settings sub-nav typesdiff --git a/docs/v5/developer/dashboard/customization/permissions.mdx b/docs/v5/developer/dashboard/customization/permissions.mdxnew file mode 100644index 0000000000..fee1d3308e--- /dev/null+++ b/docs/v5/developer/dashboard/customization/permissions.mdx@@ -0,0 +1,112 @@+---+title: Permissions+sidebarTitle: Permissions+description: How to hide UI behind CanCanCan permissions in your customisations — and why hiding is never the same as authorising.+canonical: "https://spreecommerce.org/docs/developer/dashboard/customization/permissions"+---++The dashboard exposes the current admin's CanCanCan abilities to every component via the `usePermissions()` hook. The registry surfaces — nav entries, settings entries, custom routes — also accept a `subject` shortcut, and nav entries take a generic `if` predicate that reads from `permissions`.++## Two layers++UI gating is for **UX**. Backend authorization is for **security**. They are not the same:++| Layer | Where | What it does |+|---|---|---|+| UI gating | Dashboard registries (`subject`, `if`) | Hides menu items, columns, buttons — keeps the interface tidy |+| Authorization | Rails API controllers (CanCanCan, scopes) | Refuses the request when the user doesn't have permission |++**Always rely on the backend for security.** Hiding a button is a hint to the user, not a wall. A user with browser dev tools (or the API token) can always hit the endpoint directly — your `authorize!` call is what stops them.++## The `permissions` object++```ts+interface Permissions {+ can(action: ActionName, subject: SubjectName): boolean+ cannot(action: ActionName, subject: SubjectName): boolean+ /** True when the matching rule has per-record conditions — expect possible 403s. */+ isConditional(action: ActionName, subject: SubjectName): boolean+}+```++It mirrors the backend ability at the **class level**:++```ts+permissions.can('read', 'Spree::Order')+```++Subjects are strings (`'Spree::Order'`, `'Spree::Product'`, or your own `'MyApp::Report'`). There is no client-side record-level check — when a rule is conditional on record attributes, `isConditional` returns `true` and the API is the arbiter: render the control and handle a possible 403.++## `subject` shortcut++Available on `NavEntry`, `SettingsNavEntry`, and `RouteEntry`. It hides the entry unless the user can `read` the subject:++```ts+nav.add({+ key: 'reports',+ label: 'Reports',+ path: '/reports',+ subject: 'Spree::Order', // hides nav item without read:Spree::Order+})+```++For routes, `subject` also renders a 403 page if the user navigates directly:++```ts+routes: [{+ key: 'reports',+ path: '/reports',+ component: ReportsPage,+ subject: 'Spree::Order',+}],+```++Use `subject` whenever you want a "user can read this resource" check. For anything else, use `if`.++## `if` predicate (nav entries)++`if` on a nav entry is the escape hatch. It runs at render with `{ permissions, store, user }` and returns a boolean:++```tsx+import type { Store } from '@spree/admin-sdk'++nav.add({+ key: 'reports',+ label: 'Reports',+ path: '/reports',+ if: ({ permissions, store }) =>+ permissions.can('read', 'Spree::Order') &&+ !!(store as Store | null)?.setup_tasks?.every((task) => task.done),+})+```++(The `if` context types `store` loosely — cast to the SDK's `Store` for typed access, the same way the built-in Getting Started entry does.)++Use it for combined checks (permission + store state), feature flags, multi-action checks (`can(update) && can(read)`), or anything the `subject` shortcut can't express in one string. It combines with `subject` — both must pass. (Slot entries have an `if` too, but it receives only the slot's own context — see [Slots](/v5/developer/dashboard/customization/slots).)++## Inside components++Use the `usePermissions()` hook — it returns `{ permissions, rules, isLoading }`:++```tsx+import { usePermissions } from '@spree/dashboard-core'++function ReportsPage() {+ const { permissions } = usePermissions()+ if (!permissions.can('read', 'Spree::Order')) {+ return <Forbidden />+ }+ return <ReportsList />+}+```++The same `permissions` object backs the nav registry's `if` predicate, so you can move logic between the two without changing behaviour. For declarative gating, `<Can I="update" a="Spree::Order">…</Can>` (also from `@spree/dashboard-core`) renders children only when the check passes.++## Custom permissions++If your customization introduces a new model on the backend, register it as a permission catalog resource there (`Spree.permissions.register_resource` in your engine's initializer). Its keys then appear in the role editor and the API-key scope picker, and any role granted them makes `permissions.can('read', 'MyApp::Report')` resolve in the dashboard exactly like a first-party check — the abilities ship with the current-user response (`GET /api/v3/admin/me`) at sign-in, alongside `permission_keys`, the flat key list the role editor grants from.++## Reference++- [`Permissions` interface](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/providers/permission-provider.tsx)+- [CanCanCan docs](https://github.com/CanCanCommunity/cancancan) — the Ruby ability definition languagediff --git a/docs/v5/developer/dashboard/customization/quickstart.mdx b/docs/v5/developer/dashboard/customization/quickstart.mdxnew file mode 100644index 0000000000..b91d048281--- /dev/null+++ b/docs/v5/developer/dashboard/customization/quickstart.mdx@@ -0,0 +1,103 @@+---+title: Quickstart+sidebarTitle: Quickstart+description: Add your first customization to the Spree dashboard in under 5 minutes — no npm publishing, no build configuration, just one file in your dashboard app.+canonical: "https://spreecommerce.org/docs/developer/dashboard/customization/quickstart"+---++This guide assumes two things are running:++1. A Spree API server (your Spree store's backend).+2. Your dashboard app — the small Vite project that renders the admin. In a `create-spree-app` project it lives at `apps/dashboard/`; add it to an existing project with `npx spree add dashboard`, or scaffold it anywhere with `npx spree add dashboard --template` pointing at your own copy. Start it with `pnpm dev`.++All customizations in this guide are edits to your dashboard app's own code. **You don't need to scaffold a plugin** — plugins are for [distributing features to other stores](/v5/developer/dashboard/plugins/overview).++## The 30-second example++Add an "Analytics" item to the dashboard sidebar.++**Step 1.** Open `src/plugins.ts` — the starter ships this file already wired up — and register a nav entry:++```tsx+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { BarChartIcon } from 'lucide-react'++defineDashboardPlugin({+ nav: [{+ key: 'analytics',+ label: 'Analytics',+ path: '/analytics',+ icon: BarChartIcon,+ // Built-in entries use positions 100–600 (Home … Reports).+ // 650 places Analytics after Reports, at the end.+ position: 650,+ }],+})+```++**Step 2.** Save. The dev server hot-reloads and the sidebar now shows "Analytics".++Clicking it lands on a "Page not found" screen — we registered the nav entry but no page. Let's fix that.++## Add the page++**Step 3.** Create the page component at `src/pages/analytics.tsx`:++```tsx+import { PageHeader } from '@spree/dashboard-core'+import { ResourceLayout } from '@spree/dashboard-ui'++export function AnalyticsPage() {+ return (+ <ResourceLayout+ header={<PageHeader title="Analytics" subtitle="Store performance over time" />}+ main={<p>Coming soon.</p>}+ />+ )+}+```++**Step 4.** Register the route in `src/plugins.ts`:++```tsx+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { BarChartIcon } from 'lucide-react'+import { AnalyticsPage } from './pages/analytics'++defineDashboardPlugin({+ nav: [{+ key: 'analytics',+ label: 'Analytics',+ path: '/analytics',+ icon: BarChartIcon,+ position: 650,+ }],+ routes: [{+ key: 'analytics',+ path: '/analytics',+ component: AnalyticsPage,+ }],+})+```++Save. Click "Analytics" — your page renders inside the dashboard chrome, at `/<store id>/analytics`.++<Warning>+Every `key` must be unique, including against the built-ins (`getting-started`, `home`, `orders`, `products`, `customers`, `promotions`, `reports`, `settings`). Registering a duplicate key throws at boot with a message naming the conflict.+</Warning>++## What just happened++`defineDashboardPlugin` registers extensions against the dashboard's shared registries: `nav`, `routes`, `slots`, `tables`, `settingsNav`, `formFields`, and `customFieldComponents`. Your `src/plugins.ts` runs when the app boots (the starter's `main.tsx` imports it), so everything is registered before the first render. These are the exact same APIs distributable plugins use — the only difference is packaging.++The custom route mounts under `/<store id>/analytics`. Routes registered this way are matched at navigation time, so they can even be registered lazily after boot.++Building a **distributable plugin** rather than customizing your own app? Ship pages as [file routes](/v5/developer/dashboard/customization/routes) instead — they compile into the app's route tree, so links to them are type-checked. The registry form shown here is for in-app customization.++## Next steps++- [Navigation](/v5/developer/dashboard/customization/navigation) — sidebar entries, nesting under built-in menus, settings sub-nav, permission gating+- [Routes](/v5/developer/dashboard/customization/routes) — path patterns, params, permission fallback+- [Slots](/v5/developer/dashboard/customization/slots) — inject widgets into built-in pages without forking them+- [Tables](/v5/developer/dashboard/customization/tables) — define your own list page or extend built-in tables+- [Translations](/v5/developer/dashboard/customization/translations) — add i18n keys without colliding with the frameworkdiff --git a/docs/v5/developer/dashboard/customization/routes.mdx b/docs/v5/developer/dashboard/customization/routes.mdxnew file mode 100644index 0000000000..824b8bdb24--- /dev/null+++ b/docs/v5/developer/dashboard/customization/routes.mdx@@ -0,0 +1,190 @@+---+title: Routes+sidebarTitle: Routes+description: Mount custom pages under your dashboard's `/$storeId/...` path. Supports path params, permission gating, and works alongside the dashboard's built-in routes.+canonical: "https://spreecommerce.org/docs/developer/dashboard/customization/routes"+---++The dashboard's first-party routes (`customers/`, `orders/`, `products/`, …) are file-based via TanStack Router and live in `@spree/dashboard/src/routes/`. Custom pages have two mechanisms:++1. **File routes** (packaged plugins — preferred): the plugin ships ordinary TanStack route files, and the host build compiles them into its typed route tree. Typed `<Link>`s with no casts, route-level code splitting, `validateSearch`, loaders — full router citizenship.+2. **Route registry** (in-app & dynamic): `defineDashboardPlugin({ routes })` entries matched at navigation time by a catch-all dispatcher at `/_authenticated/$storeId/$`. Use for host-app customizations (`plugins.ts`) and anything registered conditionally at runtime. File routes always win over the registry — the catch-all is the lowest-priority match.++## File routes (packaged plugins)++Declare a routes directory in your plugin's marker and put TanStack route files in it:++```jsonc+// package.json+"spree": { "dashboard": { "plugin": true, "routes": "./src/routes" } }+```++```+src/+├── pages/ # page components+└── routes/+ ├── brands.index.tsx # → /$storeId/brands+ └── brands.$brandId.tsx # → /$storeId/brands/br_123+```++```tsx+// src/routes/brands.index.tsx+import { resourceSearchSchema } from '@spree/dashboard-core'+import { createFileRoute } from '@tanstack/react-router'+import { BrandsListPage } from '../pages/brands-list'++export const Route = createFileRoute('/_authenticated/$storeId/brands/')({+ validateSearch: resourceSearchSchema,+ component: () => <BrandsListPage searchParams={Route.useSearch()} />,+})+```++Rules that make this work:++- **Commit the final composed path literal.** Plugin routes mount under the dashboard's `_authenticated/$storeId` layout; the route generator verifies the literal (and would rewrite a wrong one).+- **The host regenerates its `routeTree.gen.ts` on every dev start and build** from installed package versions — updating your plugin picks up new routes automatically (dev servers need a restart, same as installing a plugin).+- **Exclude `src/routes` from your package's standalone `tsc`** — `createFileRoute` paths only type-check against a generated tree, which exists in host programs. Develop against a dashboard host (the scaffold's tsconfig ships this exclusion).++Links to file routes are fully typed — no casts:++```tsx+<Link to="/$storeId/brands/$brandId" params={{ brandId: brand.id }}>view</Link>+```++### Route collisions++Two packages can't own the same route path. If a plugin declares a path that another plugin — or a built-in dashboard page — already claims, the build fails before generating the tree with an error naming both **packages**, the path, and each file:++```+Dashboard route collision.+Route "/_authenticated/$storeId/brands/" is declared by more than one package:+ - @acme/brands (…/node_modules/@acme/brands/src/routes/brands.index.tsx)+ - @other/brands (…/node_modules/@other/brands/src/routes/brands.index.tsx)+```++Rename one of the routes, or drop the plugin that shouldn't own it. (Duplicate paths *within* a single package are reported by the TanStack generator instead — that's an authoring bug in one package.)++<Warning>+The collision check only sees **file routes**. If a runtime-registry route (below) uses the same URL as a compiled file route, there's no build error — the file route silently wins on every navigation, because the registry's catch-all is the lowest-priority match. If a page you registered at runtime never renders, check whether an installed plugin claims the same path.+</Warning>++## Runtime route registry (in-app & dynamic)++Register from your host app's `plugins.ts` (or a plugin that genuinely needs runtime registration):++```tsx+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { ReportsPage } from './pages/reports'++defineDashboardPlugin({+ routes: [{+ key: 'reports',+ path: '/reports',+ component: ReportsPage,+ }],+})+```++`path` is **relative** to `/$storeId` — the dispatcher prepends the prefix at match time. So `/reports` matches the URL `/store_xyz/reports`. The leading `/` is required.++## Path parameters++TanStack-Router-style `$name` tokens match a single non-empty segment:++```tsx+routes: [+ { key: 'report-detail', path: '/reports/$reportId', component: ReportDetailPage },+ { key: 'report-export', path: '/reports/$reportId/export', component: ReportExportPage },+],+```++## Receiving params++Your component receives three props from the dispatcher:++```tsx+interface PluginRouteProps {+ /** Path params extracted from the URL. Keys match the `$name` tokens in your path. */+ params: Record<string, string>+ /** Always set — every route is scoped to a store. */+ storeId: string+ /** URL search-state. Pass to `<ResourceTable searchParams={searchParams} />` so filters+ * round-trip through the URL. */+ searchParams: Record<string, unknown>+}++function ReportDetailPage({ params, storeId, searchParams }: PluginRouteProps) {+ const reportId = params.reportId+ // ...+}+```++`searchParams` is typed as `Record<string, unknown>` because the dispatcher can't statically know your page's shape. If you're handing it to `<ResourceTable>`, cast to `ResourceSearch`:++```tsx+import type { ResourceSearch } from '@spree/dashboard-core'++<ResourceTable searchParams={searchParams as ResourceSearch} ... />+```++## Permission gating++A `subject` on the route entry renders a 403 fallback (instead of the page) when the user lacks `read` permission:++```tsx+routes: [{+ key: 'reports',+ path: '/reports',+ component: ReportsPage,+ subject: 'Spree::Order',+}],+```++Always pair this with a matching `subject` on the **nav entry** so users without permission never see the link in the first place. The route subject is the defensive layer for direct URLs.++`subject` is a **registry-route** feature — the dispatcher applies it before rendering. File routes don't pass through the dispatcher, so they gate themselves: check permissions inside the component with `<Can>` or `usePermissions()` from `@spree/dashboard-core` and render a fallback. Either way, this is UX only — the backend still authorizes every API call.++## Layout++Custom routes inherit the dashboard's `_authenticated` + `$storeId` layout (auth guard, sidebar, top bar, etc.) — your component renders inside the `<Outlet />`. Use `<ResourceLayout>` from `@spree/dashboard-ui` to get the same header/main/sidebar grid as core pages:++```tsx+import { PageHeader } from '@spree/dashboard-core'+import { ResourceLayout } from '@spree/dashboard-ui'++function ReportsPage() {+ return (+ <ResourceLayout+ header={<PageHeader title="Reports" backTo="dashboard" />}+ main={<ReportsList />}+ sidebar={<ReportsFilters />}+ />+ )+}+```++## Linking to a registry route++Registry routes aren't in the generated route tree, so links to them bypass static checking:++```tsx+import { Link } from '@tanstack/react-router'++<Link+ to={'/$storeId/reports/$reportId' as string}+ params={{ storeId, reportId } as never}+>+ View report+</Link>+```++The casts bypass TanStack Router's static type-checking (custom routes aren't in the generated route tree, so neither the path nor its params exist as types). Params are passed as a keyed object — each key fills the matching `$name` token.++## Order of operations++Routes register at module-load time. The dispatcher reads from the registry on **every navigation**, so route registration is much more forgiving than nav: even a route registered after first render works as soon as the user navigates to it. The only ordering rule is the usual i18n one — register your translation bundle above any registration that calls `i18n.t(...)` (see [Translations](/v5/developer/dashboard/customization/translations)).++## Reference++- [`RouteEntry`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/route-registry.ts) — full type+- [Catch-all dispatcher source](https://github.com/spree/spree/blob/main/packages/dashboard/src/routes/_authenticated/$storeId/$.tsx) — see how matching worksdiff --git a/docs/v5/developer/dashboard/customization/slots.mdx b/docs/v5/developer/dashboard/customization/slots.mdxnew file mode 100644index 0000000000..18f5edb16c--- /dev/null+++ b/docs/v5/developer/dashboard/customization/slots.mdx@@ -0,0 +1,115 @@+---+title: Slots+sidebarTitle: Slots+description: Inject your own widgets into existing dashboard pages without forking them. Slots are named injection points the dashboard exposes on built-in pages.+canonical: "https://spreecommerce.org/docs/developer/dashboard/customization/slots"+---++A slot is a named injection point in a built-in page. Components registered against a slot render inside it, sorted by `position`, gated by an optional `if` predicate. The host page knows nothing about your widget — it just renders `<Slot name="..." context={...} />` and the slot registry handles the rest.++## Quick example++Render a card with the current user's email in every page's actions dropdown:++```tsx+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { DropdownMenuItem } from '@spree/dashboard-ui'++function UserBadge({ user }: { user?: { email: string } }) {+ if (!user) return null+ return <DropdownMenuItem>{user.email}</DropdownMenuItem>+}++defineDashboardPlugin({+ slots: {+ 'page.actions_dropdown': [{+ id: 'my-user-badge',+ component: UserBadge as never,+ position: 50,+ }],+ },+})+```++`page.actions_dropdown` is one of the slots exposed by `<PageHeader>`. See the [Slots catalog](/v5/developer/dashboard/slots-catalog) for the full list and the context shape each slot provides.++## Slot context++The component receives the **slot-specific context** as props — whatever the host page passes via `<Slot name="..." context={{ product, /* etc */ }} />`. The shape varies per slot: `page.actions_dropdown` passes `{ resource }`, `product.form_sidebar` passes `{ product }`, and so on. Each slot's shape is documented in the [Slots catalog](/v5/developer/dashboard/slots-catalog).++For anything beyond the slot's own context — permissions, the current store, the signed-in user — call the hooks inside your component: `usePermissions()`, `useStore()`, `useAuth()` from `@spree/dashboard-core`. (A future release may inject these as ambient props, but today the hooks are the way.)++### Why `as never`?++`defineDashboardPlugin`'s `slots` field is typed as a generic-erased `Record<string, SlotEntry[]>` — the facade can't statically know your slot's context shape, only the host page does. Cast your component to `as never` to satisfy the registry's signature. Your component still receives the right props at runtime; the cast only suppresses the type-system noise.++If you'd rather have full type safety, call `registerSlot` directly with the explicit type parameter:++```tsx+import { registerSlot } from '@spree/dashboard-core'++interface ProductSlotContext {+ product: { id: string; brand_id?: string | null }+}++registerSlot<ProductSlotContext>('product.form_sidebar', {+ id: 'brand-card',+ component: ({ product }) => <BrandCard productId={product.id} brandId={product.brand_id} />,+ position: 50,+})+```++## Permission gating++Gate inside the component with `usePermissions()` — return `null` when the user lacks access:++```tsx+import { usePermissions } from '@spree/dashboard-core'++function AdminOnlyMenuItem() {+ const { permissions } = usePermissions()+ if (!permissions.can('manage', 'Spree::User')) return null+ return <DropdownMenuItem>…</DropdownMenuItem>+}+```++The entry-level `if` predicate also exists, but it only receives the slot's own context (the same props your component gets) — use it to skip an entry based on the host page's data, e.g. `if: ({ product }) => !!product.brand_id`. When it returns `false`, the entry is skipped entirely (no DOM nodes mounted).++## Binding to the host form++Slots on form pages (product, category, store settings — see the [slots catalog](/v5/developer/dashboard/slots-catalog#detail-page-form-slots) for which) render **inside the page's `<form>`** and expose its react-hook-form instance. A widget can register inputs against it with `useHostForm()` — they hydrate from the API, flip the Save button on change, and persist in the page's own save, with no save logic in the widget:++```tsx+import { useHostForm } from '@spree/dashboard-core'++function TechSpecsCard() {+ const form = useHostForm<{ tech_specs: string }>()+ return <Textarea {...form.register('tech_specs')} />+}+```++Pair it with a `formFields` registration so the field hydrates and ships in the payload — the full walkthrough is the [custom form field recipe](/v5/developer/dashboard/recipes/custom-form-field). Never render your own `<form>` inside a slot on these pages: HTML forbids nested forms, and the host form already owns submission. On pages without a host form (orders, customers), `useHostForm()` throws — use `useOptionalHostForm()` and fall back to your own state + API save.++## Position++`position` controls render order within the slot. Built-in entries (when the dashboard ships any) use 100/200/300 to leave gaps. Default is 100, so two entries with no explicit position render in registration order.++## Removing or updating an entry++```ts+import { removeSlot, updateSlot } from '@spree/dashboard-core'++removeSlot('product.form_sidebar', 'brand-card')+updateSlot('product.form_sidebar', 'brand-card', { position: 999 })+```++These mirror the registry's mutator pattern — useful for development-mode toggles, or for unregistering a third-party slot entry from your host.++## Order of operations++Like nav, slot entries register at module-load time and the `<Slot>` consumer re-renders via `useSyncExternalStore` when entries change. Late registration works; the slot just lights up the next render.++## Reference++- [Slots catalog](/v5/developer/dashboard/slots-catalog) — every named slot the dashboard exposes+- [`SlotEntry`, `SlotAmbientContext`, `registerSlot`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/slot-registry.ts) — full registry sourcediff --git a/docs/v5/developer/dashboard/customization/tables.mdx b/docs/v5/developer/dashboard/customization/tables.mdxnew file mode 100644index 0000000000..38de200a27--- /dev/null+++ b/docs/v5/developer/dashboard/customization/tables.mdx@@ -0,0 +1,170 @@+---+title: Tables+sidebarTitle: Tables+description: Add, change, or remove columns on built-in list tables (products, orders, customers, …), or define a table for your own resource.+canonical: "https://spreecommerce.org/docs/developer/dashboard/customization/tables"+---++Every list page in the dashboard renders through `<ResourceTable>`, which reads its column definitions from a **table registry** keyed by table name (`products`, `orders`, `customers`, …). That gives you two levers:++1. **Extend a built-in table** — add, patch, or remove columns (including their filters) without forking the page.+2. **Define your own table** — declare columns once with `defineTable`, then render them with `<ResourceTable>` on your own page.++## Add a column to a built-in table++Imperatively, from `src/plugins.ts` (or a plugin entry):++```tsx+import { tables } from '@spree/dashboard-core'++tables.products.addColumn({+ key: 'brand',+ label: 'Brand',+ default: true, // visible out of the box+ render: (product) => product.brand?.name ?? '—',+})+```++Or declaratively through `defineDashboardPlugin` — same effect, grouped with your other extensions:++```tsx+defineDashboardPlugin({+ tables: {+ products: {+ add: [{ key: 'brand', label: 'Brand', default: true, render: (p) => p.brand?.name ?? '—' }],+ },+ },+})+```++New columns append after the existing ones. Column keys must be unique per table — adding a duplicate throws with a message telling you to use `updateColumn` instead.++<Note>+**Timing is taken care of.** Built-in tables register when their page first loads, which may be after your code runs. Mutations against a table that isn't registered yet are queued and replayed the moment it appears — and mutations against a table that never registers simply never fire. That means extending an optional feature's table is safe even when that feature isn't installed.+</Note>++## Modify or remove built-in columns++```tsx+tables.products.updateColumn('price', { label: 'Retail price' })+tables.products.removeColumn('cost_price')+```++Declaratively:++```tsx+defineDashboardPlugin({+ tables: {+ products: {+ update: { price: { label: 'Retail price' } },+ remove: ['cost_price'],+ },+ },+})+```++`updateColumn` patches shallowly — pass only the fields you want to change. `removeColumn` of an unknown key is a no-op.++## Column definition++```ts+interface ColumnDef<T> {+ key: string // unique per table; also the default Ransack sort/filter attribute+ label: string // header text — use i18n.t(...) for translated labels+ render?: (row: T) => ReactNode // cell renderer; defaults to rendering row[key] as text+ className?: string // cell class (e.g. 'text-right tabular-nums')+ default?: boolean // part of the visible column set out of the box+ sortable?: boolean // header toggles Ransack sort on the attribute+ filterable?: boolean // appears in the filter panel+ ransackAttribute?: string // backend attribute when it differs from key+ displayable?: boolean // set false for filter-only entries (no column rendered)+}+```++### Filter types++When a column is `filterable`, `filterType` decides which filter UI it gets:++| `filterType` | Filter UI | Extra fields |+|---|---|---|+| `'string'` (default) | Text input with contains/equals operators | — |+| `'boolean'` | Yes/no toggle | — |+| `'number'`, `'currency'` | Numeric comparisons | — |+| `'date'` | Date range picker (store-timezone aware) | — |+| `'enum'` | Fixed option list | `filterOptions: [{ value, label }]` (required) |+| `'resource'` | Multi-select autocomplete against another resource | `filterResource` (required) — `queryKey`, `search`, `hydrate`, `getOptionLabel` |+| `'tags'` | Tag autocomplete | `taggableType` (required), e.g. `'Spree::Product'` |++A `'resource'` filter searches as the admin types and resolves already-selected IDs back to labels on page reload:++```tsx+tables.products.addColumn({+ key: 'brand_id',+ label: 'Brand',+ displayable: false, // filter only — no column in the table+ filterable: true,+ filterType: 'resource',+ filterResource: {+ queryKey: 'brands',+ search: (query) => brandsClient.list({ q: { name_cont: query } }),+ hydrate: (ids) => brandsClient.list({ q: { id_in: ids } }),+ getOptionLabel: (brand) => brand.name,+ },+})+```++Filtering and sorting are executed by the Admin API (Ransack), not in the browser — `key` (or `ransackAttribute`) must be a filterable/sortable attribute the API allows.++## Define your own table++For your own list page, declare the table once — typically right next to your `defineDashboardPlugin` call:++```tsx+import { defineTable } from '@spree/dashboard-core'++defineTable<Brand>('brands', {+ title: 'Brands',+ searchParam: 'search',+ searchPlaceholder: 'Search by name…',+ defaultSort: { field: 'name', direction: 'asc' },+ emptyMessage: 'No brands yet',+ columns: [+ { key: 'name', label: 'Name', sortable: true, filterable: true, default: true },+ { key: 'products_count', label: 'Products', default: true, className: 'text-right tabular-nums' },+ { key: 'created_at', label: 'Created', sortable: true, default: false },+ ],+})+```++Then render it from your page component:++```tsx+<ResourceTable<Brand>+ tableKey="brands" // which table definition to read+ queryKey="brands" // TanStack Query cache key+ queryFn={(params) => brandsClient.list(params)}+ searchParams={searchParams}+/>+```++`<ResourceTable>` handles pagination, sorting, the filter panel, column visibility, and URL round-tripping of all of it. See [Routes](/v5/developer/dashboard/customization/routes) for the page around it — the [example Brands plugin](https://github.com/spree/spree/tree/main/packages/dashboard-plugin-example) shows the complete wiring.++## Bulk actions, row actions, reordering++These are **props on `<ResourceTable>`**, composed by the page that renders the table:++```tsx+<ResourceTable<Brand>+ // …+ bulkActions={[{ key: 'archive', label: 'Archive selected', onSelect: async (rows) => { /* … */ } }]}+ rowActions={(row) => <BrandRowMenu brand={row} />}+/>+```++Use them freely on your own pages. They are **not registry-driven** — a plugin can't inject bulk or row actions into a built-in page's table today. If a built-in page needs an injection point, that's what [slots](/v5/developer/dashboard/customization/slots) are for.++## Reference++- [`table-registry.ts`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/table-registry.ts) — `defineTable`, `tables`, the full `ColumnDef` union+- [`<ResourceTable>`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/components/resource-table.tsx) — props for bulk actions, row actions, drag-reordering+- [Example Brands plugin](https://github.com/spree/spree/tree/main/packages/dashboard-plugin-example) — a real `defineTable` + `<ResourceTable>` + products-column extensiondiff --git a/docs/v5/developer/dashboard/customization/translations.mdx b/docs/v5/developer/dashboard/customization/translations.mdxnew file mode 100644index 0000000000..764e12f2d6--- /dev/null+++ b/docs/v5/developer/dashboard/customization/translations.mdx@@ -0,0 +1,99 @@+---+title: Translations+sidebarTitle: Translations+description: Add your own i18n strings to the dashboard so labels, validation messages, and notifications respect the admin's chosen locale.+canonical: "https://spreecommerce.org/docs/developer/dashboard/customization/translations"+---++The dashboard uses [i18next](https://www.i18next.com/) with the `react-i18next` bindings. All strings live in i18next's default `translation` namespace, with every key under a top-level `admin.` prefix (`admin.nav.orders`, `admin.fields.<resource>.<attribute>.label`, …). You register your strings into the same namespace with the same prefix so they look and feel native.++## Add translations++```ts+import { i18n } from '@spree/dashboard-core'++i18n.addResourceBundle('en', 'translation', {+ admin: {+ reports: {+ title: 'Reports',+ empty: 'No reports yet.',+ },+ fields: {+ report: {+ name: { label: 'Report name', placeholder: 'e.g. Q4 sales by region' },+ },+ },+ },+}, /* deep */ true, /* overwrite */ true)+```++With `deep: true` your keys merge into the existing tree instead of replacing it; `overwrite: true` lets your bundle win where a key genuinely collides (this is what the framework and the official plugins use). Note the `admin` wrapper is part of the **bundle contents** — the namespace argument stays `'translation'`.++Repeat per locale:++```ts+import de from './locales/de.json'+import en from './locales/en.json'+import fr from './locales/fr.json'++for (const [locale, bundle] of Object.entries({ en, fr, de })) {+ i18n.addResourceBundle(locale, 'translation', bundle, true, true)+}+```++## Use them++```tsx+import { useTranslation } from 'react-i18next'++function ReportsHeader() {+ const { t } = useTranslation()+ return <h1>{t('admin.reports.title')}</h1>+}+```++In a registry entry, pass the key directly:++```ts+nav.add({+ key: 'reports',+ label: i18n.t('admin.reports.title'),+ path: '/reports',+})+```++Note: `i18n.t` resolves at the call site, so the label is a snapshot taken at registration time. Registry entries store plain strings — if the user switches language without a reload, registered labels keep their old language until re-registered. Components that call `useTranslation()` re-render on locale change; registry labels don't. If that matters for your entry, re-register it on the i18n `languageChanged` event.++## Field-key convention++Form labels, placeholders, and help text follow a two-level key convention:++1. `admin.fields.<resource>.<attribute>.<facet>` — resource-specific, e.g. `admin.fields.report.name.label`+2. `admin.fields.<attribute>.<facet>` — cross-resource defaults, e.g. `admin.fields.name.label`++Components call `t()` with these keys explicitly — pick the resource-scoped form for labels that differ per resource, and reuse the shared `admin.fields.<attribute>.<facet>` keys the framework already ships for common attributes (`name`, `email`, `created_at`, `storefront_visible`, …).++In dev mode, missing keys log to the console (in production a missing key falls back to a humanized version of the attribute name).++## Server-side error messages++The `mapSpreeErrorsToForm` helper routes 422 responses onto `form.formState.errors`, but the messages themselves are the **server's strings, verbatim** — `{ "name": ["can't be blank"] }` becomes a field error reading "can't be blank". To localize validation messages, configure the locale on the backend (Rails i18n translates ActiveRecord error messages); the dashboard displays whatever the API returns.++## Order of operations++Register translations **before** any code that calls `i18n.t()` at module-load time (registry labels, table titles, etc.). The framework's own bundles are loaded before your code runs, so the pattern is simply — top of the file:++```tsx+// src/plugins.ts (same pattern in a plugin package's entry module)+import { defineDashboardPlugin, i18n } from '@spree/dashboard-core'+import en from './locales/en.json'++i18n.addResourceBundle('en', 'translation', en, true, true) // ① translations first++defineDashboardPlugin({ /* ② registrations may now use i18n.t(...) */ })+```++## Reference++- [i18next docs](https://www.i18next.com/) — full API+- The dashboard's own bundle: [`packages/dashboard/src/locales/en.json`](https://github.com/spree/spree/blob/main/packages/dashboard/src/locales/en.json) — copy keys for forms, status badges, validation messages, etc.diff --git a/docs/v5/developer/dashboard/deployment.mdx b/docs/v5/developer/dashboard/deployment.mdxnew file mode 100644index 0000000000..b2907dd36d--- /dev/null+++ b/docs/v5/developer/dashboard/deployment.mdx@@ -0,0 +1,79 @@+---+title: Deploying the dashboard+sidebarTitle: Deployment+description: Ship the React Dashboard to production — served by the Spree server itself (the default), or as a static build on a CDN.+canonical: "https://spreecommerce.org/docs/developer/dashboard/deployment"+---++The dashboard deploys as **static files**. `vite build` produces `dist/` — HTML, JS, CSS — there is no Node server in production. What varies is who serves those files.++<Warning>+`VITE_`-prefixed values are compiled into the client bundle — never put credentials in them. The dashboard authenticates admins interactively (JWT in memory + an httpOnly refresh cookie); no API keys are involved.+</Warning>++## Single node — the default++The Spree server serves the dashboard itself at **`/dashboard`**: one container, one origin, zero CORS or cookie configuration. The official Spree Docker image ships with the stock dashboard baked in — deploy the image anywhere Docker runs (Render, Railway, AWS, Azure, your own host) and `https://your-api-host/dashboard` just works.++Under the hood, the **`spree_dashboard` gem** (in the Gemfile of the starter and the official image) serves the directory in `Spree::Dashboard.dist_path` — or the `SPREE_DASHBOARD_DIST_PATH` env var — with SPA semantics: every dashboard route falls back to `index.html`, hashed assets get immutable caching. The bundle is built with a **relative API base** (`VITE_SPREE_API_URL` unset) and `base: /dashboard/`, so the same image works on every host and environment with no rebuild. API-only deployments simply omit the gem.++### Custom dashboard, single node++The official image contains the *stock* dashboard. Once you've customized yours (your own pages/plugins in `apps/dashboard/`), bake your build into your own image:++```bash+spree build --production # optionally --tag registry/repo:tag+```++The Dockerfile normalizes its own build context: built from the project root it detects the layout (`backend/` = the Rails app, `apps/dashboard/` = your dashboard) and builds *your* dashboard into the image — no flags, no named contexts. Without the CLI, the equivalent is:++```bash+docker build . -f backend/Dockerfile -t my-shop-spree:latest+```++Inside the dashboard stage the build runs with `VITE_BASE_PATH=/dashboard/` (asset URLs resolve under the mount) and `VITE_SPREE_API_URL` unset (API calls stay origin-relative); the Node toolchain lives only in that throw-away stage. Projects **without** `apps/dashboard/` get the stock dashboard baked instead — and if your `backend/Dockerfile` predates this layout support, the command warns instead of silently shipping the stock dashboard over your customized one (update it from the spree-starter template).++## Static host / CDN — the alternative++For edge-served assets or an independent dashboard release cadence, deploy `dist/` to a static host on its own domain:++```bash+cd apps/dashboard+VITE_SPREE_API_URL=https://api.mystore.com pnpm build+```++This is the **cross-origin** topology, with three requirements:++1. **HTTPS on both sides.** The refresh cookie is issued with `SameSite=None; Secure` in production, and browsers drop `Secure` cookies over HTTP. There is no insecure-production mode.+2. **Allowed Origins.** Add the dashboard's URL (e.g. `https://dashboard.mystore.com`) to **Settings → Allowed Origins** in the Spree admin — the API rejects cross-origin requests until then.+3. **SPA fallback.** Every path must rewrite to `index.html` so the router owns the URL (`/* → /index.html` on your host: `_redirects` on Netlify, `vercel.json` rewrites, `try_files $uri /index.html;` on nginx).++A middle ground also works: serve `dist/` and proxy `/api/*` + `/rails/*` to Rails from one domain behind your own nginx/Caddy/ingress — same-origin simplicity without baking the bundle into the image.++## Render++The Blueprint that `create-spree-app` places at the project root deploys the backend as a **Docker service** built from your repo — the same Dockerfile as everywhere else, with the repo root as context:++```yaml+runtime: docker+dockerfilePath: ./backend/Dockerfile+dockerContext: .+```++That's the whole setup — one service, one origin, **your customized dashboard** (it builds from your `apps/dashboard`, not the stock bundle) at `https://your-service.onrender.com/dashboard`. No `VITE_SPREE_API_URL`, no Allowed Origins entry, no extra service, no build commands to maintain — migrations run from the image entrypoint on boot. Redeploys rebuild on every push, and what Render builds is byte-for-byte what `spree build --production` builds locally.++If you prefer the dashboard on Render's CDN instead, add a static-site service by hand using the cross-origin recipe above.++## Any other static host++The same three ingredients, by hand: build with `VITE_SPREE_API_URL` set, upload `dist/`, configure the `/* → /index.html` rewrite. Then add the origin to Allowed Origins.++## Checklist (cross-origin only)++Single-node deployments skip all of this — one origin needs none of it.++- [ ] `VITE_SPREE_API_URL` points at the production API (baked at build time — one build per environment)+- [ ] HTTPS on the dashboard *and* the API+- [ ] Dashboard origin added to **Settings → Allowed Origins**+- [ ] All paths rewrite to `index.html`+- [ ] No secrets in any `VITE_` variablediff --git a/docs/v5/developer/dashboard/overview.mdx b/docs/v5/developer/dashboard/overview.mdxnew file mode 100644index 0000000000..ccbbd3428b--- /dev/null+++ b/docs/v5/developer/dashboard/overview.mdx@@ -0,0 +1,108 @@+---+title: React Dashboard Overview+sidebarTitle: Overview+description: Learn about the Spree React Dashboard architecture and how to customize it and extend it+canonical: "https://spreecommerce.org/docs/developer/dashboard/overview"+---++<Info>+The React Dashboard is currently a **Developer Preview** — APIs may still change between releases.+In Spree 6 it will become the default Admin interface replacing the Spree 5 admin.+</Info>++The React Dashboard is a React single-page application (SPA) that talks to the [Spree Admin API](/api-reference/admin-api). It can be distributed with the Spree API or as a standalone npm package, and it can be extended with plugins. The dashboard is built with modern React libraries and patterns, including:++| Layer | Choice |+|---|---|+| Build & dev | [Vite](https://vitejs.dev/) |+| Routing | [TanStack Router](https://tanstack.com/router) (file-based, type-safe) |+| Data fetching | [TanStack Query](https://tanstack.com/query) |+| Forms | [React Hook Form](https://react-hook-form.com/) + [Zod](https://zod.dev/) |+| UI primitives | [shadcn/ui](https://ui.shadcn.com/) + [Base UI](https://base-ui.com/) + [Tailwind CSS](https://tailwindcss.com/) |+| Icons | [lucide-react](https://lucide.dev/) |+| Charts | [Recharts](https://recharts.org/) |+| Rich text | [Tiptap](https://tiptap.dev/) |+| Notifications | [Sonner](https://sonner.emilkowal.ski/) |+| Lint & format | [Biome](https://biomejs.dev/) |++### Packages++Dashboard consinsts of 3 NPM packages, each with a different purpose. You can import any of them in your host app or plugin package.++| Package | What it contains | When you touch it |+|---|---|---|+| `@spree/dashboard-ui` | Design system: [shadcn](https://ui.shadcn.com/) primitives + headless composed components (`PageHeader`, `ResourceLayout`, `ResourceTable`'s rendering layer, etc.) + design tokens | Building custom UI — primitives + compounds you can drop anywhere |+| `@spree/dashboard-core` | Framework: registries (nav, route, slot, table, settings-nav), providers (auth, permission, store), admin SDK client, infra hooks, the `defineDashboardPlugin` API | Extending the admin — every customization API lives here |+| `@spree/dashboard` | The deployable SPA: routes, resource hooks, schemas, locale strings, app shell | Replacing or restyling specific routes (rare) |++Most customization happens via `@spree/dashboard-core`. You import its registries from your own host-app code (or from a separate plugin package) to add nav entries, routes, slot widgets, table columns, and translations.++You can also built your own dashboard using `@spree/dashboard-ui` primitives and `@spree/dashboard-core` registries, if you want to replace the default dashboard entirely. This is rare — most teams just add a few pages or cards to the existing dashboard.++## Get the dashboard++Your copy of the dashboard is a small Vite app (the "host app") that imports `<Dashboard />` from `@spree/dashboard` — you own its `package.json`, Vite config, and a `src/plugins.ts` for customizations. Two ways to get one:++- **New project:** `npx create-spree-app my-store` — answer **Yes** to "Include React Dashboard?" and it lands in `apps/dashboard/`, pointed at your API.+- **Existing project:** run `npx spree add dashboard` from your project root — same result.++Either way: `cd apps/dashboard && npm run dev`, open http://localhost:5173, and sign in with your admin email and password. No API keys to configure — admins authenticate interactively.++## Choose your path++There are two ways to customize the dashboard. **Both use the same APIs** — the only difference is packaging.++### 1. Customize in your host app (Recommended)++You're building a Spree store and want a "Featured products" page or a custom card on every product detail. Edit your dashboard app directly — it ships a `src/plugins.ts` file for exactly this (in a `create-spree-app` project the dashboard app lives at `apps/dashboard/`):++```tsx+// src/plugins.ts — already imported by the app; just add your registrations+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { MyAnalyticsPage } from './pages/analytics'++defineDashboardPlugin({+ nav: [{ key: 'analytics', label: 'Analytics', path: '/analytics', position: 650 }],+ routes: [{ key: 'analytics', path: '/analytics', component: MyAnalyticsPage }],+})+```++That's the entire setup. No npm publishing, no peer dependencies, no build configuration — you're inside the app's own build, so styling and hot reload just work. Most teams stop here.++→ Start at the [**customization quickstart**](/v5/developer/dashboard/customization/quickstart).++### 2. Ship a redistributable plugin++You're building a feature that multiple Spree stores will install — a Brands gem, a Wishlists integration, a Stripe Tax connector. Package the customization as an npm module so any host app can install it with a single `pnpm add my-plugin`.++This adds three concerns on top of in-app customization:++- **Peer-dependency rules** so your plugin's `@spree/dashboard-core` resolves to the host's instance (registries are module singletons — see [Publishing](/v5/developer/dashboard/plugins/publishing))+- **Auto-discovery** — the dashboard's build finds every installed dependency carrying the `spree.dashboard.plugin` marker, activates it, and wires up its styling. Installing a plugin is `pnpm add` + a dev-server restart; nothing to edit. See [Distributing](/v5/developer/dashboard/plugins/distributing) for how it works and the explicit-whitelist escape hatch.+- **File routes** — a plugin ships its pages as TanStack file routes that get compiled into the app's route tree, so links to plugin pages are fully type-checked. See [Routes](/v5/developer/dashboard/customization/routes). (In-app customizations use the simpler `routes:` registry instead, as above.)+- **A backend half** — a Rails extension gem that ships the API endpoints your dashboard plugin calls++The `@spree/cli` scaffolds the dashboard half for you:++```bash+npx @spree/cli plugin new my-feature+```++→ Start at the [**plugin scaffolding guide**](/v5/developer/dashboard/plugins/scaffolding).++## Which one should I pick?++Use this rule of thumb:++- **Customize in-app** if the feature is store-specific (your branding, your team's workflow, your custom domain logic) or you don't yet know whether others would want it. The cost to "promote" it to a plugin later is small.+- **Ship a plugin** if you're certain others will install it (you're publishing to the marketplace, your agency is rolling it out across clients, the feature has a clear standalone identity).++When in doubt, customize in-app first. The migration path to a plugin is mechanical — same APIs, just wrapped in their own package.++## Reference++- [Customization quickstart](/v5/developer/dashboard/customization/quickstart)+- [Plugin scaffolding](/v5/developer/dashboard/plugins/scaffolding)+- [Slots catalog](/v5/developer/dashboard/slots-catalog) — every named slot the dashboard exposes+- [`@spree/dashboard-core` README](https://github.com/spree/spree/tree/main/packages/dashboard-core) — full extension API reference+- [Classic Admin extension model](/v5/developer/admin/extending-ui) — for Spree 5.xdiff --git a/docs/v5/developer/dashboard/plugins/distributing.mdx b/docs/v5/developer/dashboard/plugins/distributing.mdxnew file mode 100644index 0000000000..5b2f4fb453--- /dev/null+++ b/docs/v5/developer/dashboard/plugins/distributing.mdx@@ -0,0 +1,138 @@+---+title: Distributing+sidebarTitle: Distributing+description: What consumers do to install your plugin — the wiring on the host side, what to document, and how to keep upgrades painless.+canonical: "https://spreecommerce.org/docs/developer/dashboard/plugins/distributing"+---++This page is the *consumer's* perspective on installing your plugin. Cover it in your README so users have a one-page reference.++## The two steps++A consumer installing your plugin needs to:++1. **Install the npm package** — `pnpm add @your-scope/your-plugin`, then restart the dev server+2. **Apply any backend changes** — usually adding a Rails gem, running migrations++```bash+pnpm add @your-scope/your-plugin++# Rails side, if your plugin has a backend+bundle add your_plugin+bin/rails generate your_plugin:install+bin/rails db:migrate+```++**No host-code edit.** As long as your plugin's `package.json` declares the `spree.dashboard.plugin` marker (the CLI scaffold does this for you — see [Publishing](/v5/developer/dashboard/plugins/publishing#tell-the-vite-plugin-where-to-find-you)), `spreeDashboardPlugin()` walks the host's dependencies at build time and finds it automatically. Discovery feeds two things:++- **Activation** — the app entry imports `virtual:spree-dashboard-plugins` (the dashboard app shell and the starter template already do), a module the Vite plugin synthesizes with one side-effect import per discovered plugin. Your `defineDashboardPlugin` call runs before first render without the host touching `main.tsx`.+- **Tailwind scanning** — your plugin's class names compile without any extra wiring.++Installing a package activating its code in the admin is the same trust model as adding a gem to a Rails `Gemfile` — vet your dependencies. Hosts that want explicit control use the whitelist below.++Plugins that take configuration (the `definePlugin(config)` factory pattern — see below) are the exception: the factory call is host code, so the host imports and invokes it in `main.tsx` themselves.++### Manual whitelist (advanced)++For tightly controlled environments (a host that wants explicit allowlist semantics, or a plugin you want to load conditionally), pass the names explicitly:++```ts+// vite.config.ts (your dashboard app)+spreeDashboardPlugin({+ plugins: ['@your-scope/your-plugin'], // disables auto-discovery+})+```++Passing `plugins: []` disables auto-discovery entirely — useful if you want to ship a vanilla dashboard with zero third-party Tailwind sources.++## Dev-mode banner++If the consumer registers your plugin explicitly but it's not installed (or the spelling is off), `@spree/dashboard-core/vite` shows a Vite error overlay during dev with the package name and a fix-it checklist. The same overlay fires if a discovered plugin can't be resolved on disk. That replaces the older silent-failure mode where missing plugins emitted unstyled HTML.++## What to put in your README++A README that gets users to "working in five minutes" has:++- A one-paragraph "what this does"+- Screenshots or a short clip of the dashboard UI it adds+- The four install steps (literally copy-paste blocks)+- A "configuration" section if the plugin has runtime config+- A "compatibility" table (`@spree/dashboard >=6.0.0`, `Spree >=6.0.0`, etc.)+- Links to the source for slots/components the plugin overrides++Skip the "philosophy" and the "alternative approaches" sections. Get users to working in minutes.++## Configuration patterns++Plugins occasionally need runtime config — API endpoints, feature toggles, custom permissions. Two patterns:++### Module-level `configure` call++```ts+// in your plugin+let _config = { endpoint: '/default' }+export function configure(opts: { endpoint?: string }) {+ _config = { ..._config, ...opts }+}+export function getConfig() { return _config }+```++```ts+// consumer+import { configure } from '@your-scope/your-plugin'+configure({ endpoint: '/custom' })+```++Simple, no dependencies — but mind the timing: ES module imports are hoisted, so the plugin module (including any top-level `defineDashboardPlugin` call) always executes **before** your `configure(...)` line runs. This pattern therefore only works for values the plugin reads lazily — at render or fetch time, like an API endpoint — never for anything its import-time registration depends on. If config shapes what gets registered (which nav entries, which routes), use the factory pattern below instead.++### `definePlugin(config)` factory++```ts+// in your plugin+export function definePlugin(config: PluginConfig) {+ // call defineDashboardPlugin inside, closing over config+}+```++```ts+// consumer+import { definePlugin } from '@your-scope/your-plugin'+definePlugin({ endpoint: '/custom' })+```++A bit more boilerplate but easier to test, and the order is unambiguous — no side-effect-at-import-time. If you go this route, drop the auto-registering entry-point and document `definePlugin` as *the* way to install.++## Upgrades++When you cut a major version of your plugin, the breaking-changes section of your changelog needs to call out:++- Renamed registry keys (`nav.add({ key: ... })` changes are user-visible — their URLs depend on it)+- Locale-key renames (consumers may have overrides keyed off old names)+- Slot ID changes (consumers extending your slots break)+- `peerDependencies` range bumps (consumers may need to upgrade Spree first)++Treat the plugin's public surface as: nav keys, route paths, slot IDs, locale keys, and the exported `configure` / `definePlugin` API. Everything else is internal.++## Coexistence with other plugins++The registries are global singletons, so a key collision is the consumer's problem to debug. Mitigations:++- **Namespace your keys** — `key: 'acme-brands'` not `key: 'brands'`.+- **Namespace locale keys** — `admin.acme_brands.title` not `admin.brands.title`.+- **Namespace API paths** — your Rails engine should mount under `/api/v3/admin/acme/...`, not `/api/v3/admin/brands` (which collides with core Brands if it ever ships).++The dashboard logs a warning in dev mode when two registry entries share a key. That's the consumer's signal that two plugins are stepping on each other — and it falls back to "last-registered wins", which is rarely what either plugin wanted.++## Distribution channels++- **npm public** — what most plugins want. `pnpm publish --access public`.+- **npm private (paid)** — for commercial plugins; combine with a license key checked at runtime.+- **GitHub Package Registry** — internal-only; consumers add `@your-scope:registry=https://npm.pkg.github.com` to `.npmrc`.+- **Git tarball** — `pnpm add github:your-org/your-plugin#main` works for unpublished plugins, useful while iterating against a single consumer.++For pre-1.0 plugins, ship under the `next` dist-tag (`pnpm publish --tag next`) so `pnpm add @your-scope/your-plugin` resolves to the stable line and `pnpm add @your-scope/your-plugin@next` opts in.++## Reference++- [Example consumer wiring](https://github.com/spree/spree/blob/main/packages/dashboard/vite.config.ts) — what `spreeDashboardPlugin` looks like in production+- [Plugins reference (`brands` example)](https://github.com/spree/spree/tree/main/packages/dashboard-plugin-example) — what a finished plugin looks like end-to-enddiff --git a/docs/v5/developer/dashboard/plugins/overview.mdx b/docs/v5/developer/dashboard/plugins/overview.mdxnew file mode 100644index 0000000000..9c1ecf6cfa--- /dev/null+++ b/docs/v5/developer/dashboard/plugins/overview.mdx@@ -0,0 +1,47 @@+---+title: Plugin overview+sidebarTitle: Overview+description: Package dashboard customizations as a redistributable npm plugin. Read this if you're shipping a feature for *other* people's Spree projects — not your own.+canonical: "https://spreecommerce.org/docs/developer/dashboard/plugins/overview"+---++If you're customizing the dashboard for your own project, you don't need a plugin. Drop the same code into `src/plugins.ts` in your dashboard app and skip this section entirely — start with the [Customization](/v5/developer/dashboard/customization/quickstart) docs.++This section is for the ~10% of cases where you want to **distribute** dashboard extensions: as an open-source integration, an internal package shared across multiple host apps, or a SaaS-style commercial add-on.++## What "plugin" means here++A dashboard plugin is:++1. **An npm package** — published, versioned, installed via `pnpm add @your-scope/your-plugin`.+2. **One side-effecting entry-point** — `import '@your-scope/your-plugin'` calls `defineDashboardPlugin({ ... })` at module-load time, which registers nav entries, routes, slots, columns, etc.+3. **Auto-discovered** — the `"spree": { "dashboard": { "plugin": true } }` marker in your package.json is all the host needs; `spreeDashboardPlugin()` finds every installed dependency carrying it, activates the entry-point, and scans your source for Tailwind classes so you never ship pre-built CSS. (Hosts can pass an explicit `plugins: [...]` array to opt out of discovery and whitelist instead.)+4. **Translations-aware** — your bundle ships JSON locale files and calls `i18n.addResourceBundle('en', 'translation', bundle, true, true)` on import (keys nested under a top-level `admin` object).+5. **Possibly Rails-aware** — many plugins also ship a Rails engine alongside the dashboard package (new models, new API endpoints) so the dashboard has something to talk to.++That's it. **Plugins use the exact same registries as in-app customizations.** Everything you can do in `src/plugins.ts` you can also do from inside a plugin entry-point. The split between "in-app" and "plugin" is about packaging and distribution, not capability.++## When to choose plugin over in-app++| Scenario | Approach |+|---|---|+| Single project, your own team | In-app customization |+| Two-three internal projects sharing the same extension | Internal npm package (still a plugin) |+| Open-source integration distributed via npm | Plugin |+| Commercial add-on with versioning + changelog | Plugin |+| One-off prototype, even at a client | In-app (you can extract later) |++If you're not sure: start in-app. Lifting `src/plugins.ts` into a plugin package later is a half-hour refactor — moving in the other direction is more painful.++## What's in this section++- [Scaffolding](/v5/developer/dashboard/plugins/scaffolding) — `spree plugin new <name>` generates the monorepo+- [Publishing](/v5/developer/dashboard/plugins/publishing) — package metadata, semver, the npm bits+- [Distributing](/v5/developer/dashboard/plugins/distributing) — what consumers do to install it++If you haven't yet, read the [Customization](/v5/developer/dashboard/customization/quickstart) section first. It's where the registry API is documented; the plugin pages mostly cover *packaging* concerns.++## Reference++- [Reference: Plugin example (`brands` repo)](https://github.com/spree/spree/tree/main/packages/dashboard-plugin-example) — vendored reference implementation+- [`defineDashboardPlugin` source](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/plugin.ts)diff --git a/docs/v5/developer/dashboard/plugins/publishing.mdx b/docs/v5/developer/dashboard/plugins/publishing.mdxnew file mode 100644index 0000000000..84855be26c--- /dev/null+++ b/docs/v5/developer/dashboard/plugins/publishing.mdx@@ -0,0 +1,143 @@+---+title: Publishing+sidebarTitle: Publishing+description: Get a dashboard plugin onto npm — package metadata, peer dependencies, TypeScript builds, versioning with Changesets.+canonical: "https://spreecommerce.org/docs/developer/dashboard/plugins/publishing"+---++`@spree/cli plugin new` scaffolds the npm package shape, but you still need to fill in publishing-specific metadata before `pnpm publish`. This page covers what to set and why.++## Set the right `peerDependencies`++Your plugin imports React, the dashboard, Tailwind, i18next, etc., but **you don't bundle them** — the host app has those, and bundling them twice causes either duplicate module instances or a tree-shaken nightmare. Use `peerDependencies`:++```json+{+ "peerDependencies": {+ "react": "^19",+ "react-dom": "^19",+ "@spree/dashboard-core": "^0.10.0",+ "@spree/dashboard-ui": "^0.10.0",+ "@spree/admin-sdk": "^0.6.0",+ "i18next": "^26",+ "react-i18next": "^17",+ "@tanstack/react-query": "^5",+ "@tanstack/react-router": "^1",+ "lucide-react": "^1"+ }+}+```++Use ranges, not exact versions — pin too tightly and consumers can't upgrade the dashboard without you cutting a release. One Developer Preview caveat: for `0.x` versions, `^` only allows patch-level drift (`^0.10.0` matches `0.10.x`, not `0.11.0`), so expect to bump your `@spree/dashboard-*` peers alongside dashboard releases until 1.0. `spree plugin new` scaffolds these ranges for you, matched to the current release.++`dependencies` is for things your plugin *uses* that the host *doesn't* — small utilities (e.g., `clsx`, `date-fns` if you need a specific version, your own helper packages). When in doubt, peer-dep it. The trade-off is "user has to install one more thing" vs. "user has two copies of React" — always pay the first cost.++## Choose what to publish++The scaffold's `package.json` ships TS source by default. Two options:++### Option A — Ship pre-built JS++Run `tsup` on publish, ship `dist/`:++```json+{+ "main": "./dist/index.cjs",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "files": ["dist", "src/locales"],+ "scripts": {+ "build": "tsup src/index.tsx --format cjs,esm --dts --external react",+ "prepublishOnly": "pnpm build"+ }+}+```++Pre-built JS is friendlier to consumers using non-Vite bundlers and means your code runs regardless of the host's TS config.++### Option B — Ship source++```json+{+ "main": "./src/index.tsx",+ "types": "./src/index.tsx",+ "files": ["src"]+}+```++Vite + tsup can consume TSX directly. Simpler builds, hot reload across the boundary in dev, but only works for Vite-host consumers. Spree dashboards always use Vite, so this is safe in practice.++Pick A if you're going to npm in earnest. Pick B for internal-only packages used inside a known-Vite setup.++## Side-effects flag++The plugin's whole purpose is side effects (`defineDashboardPlugin` registers stuff at module-load time). **Tell bundlers not to tree-shake it:**++```json+{+ "sideEffects": ["./src/index.tsx", "./dist/index.js", "./dist/index.cjs"]+}+```++Without this, a bundler can decide that `import '@your-scope/your-plugin'` does nothing useful and drop it. The list is what's allowed to have effects; everything else still tree-shakes.++## Tell the Vite plugin where to find you++Declare your package as a dashboard plugin in its own `package.json`:++```json+{+ "spree": {+ "dashboard": {+ "plugin": true,+ "routes": "./src/routes"+ }+ }+}+```++`routes` (optional) points at your TanStack file-routes directory; the host build compiles it into its typed route tree — see the [routes guide](/v5/developer/dashboard/customization/routes).++This marker is what powers **auto-discovery**: when a host calls `spreeDashboardPlugin()` without an explicit `plugins` array (the default), the Vite plugin walks the host's `package.json` deps + devDeps, reads each one's manifest, and picks up anything with `spree.dashboard.plugin: true`. The host doesn't have to know your plugin's name — `pnpm add @your-scope/your-plugin` is the entire installation step.++The CLI scaffold (`spree plugin new`) writes this field for you. If you're hand-rolling a plugin, add it before publishing — without it, hosts that rely on auto-discovery won't find your plugin and Tailwind won't pick up your class names.++## Export the Tailwind source++`spreeDashboardPlugin` uses `require.resolve(...)` to find your package, then walks `src/` for Tailwind class scanning. As long as you ship `src/`, it works — Tailwind picks up `className="..."` strings from your built code without you publishing CSS.++If you only ship `dist/` and your built code mangles class names (Tailwind can't see `text-${variant}-500`), use static class names or expose a `tailwind.config.js` content array.++## Versioning with Changesets++Spree's own packages are versioned with [Changesets](https://github.com/changesets/changesets); plugin authors don't have to use it, but it pairs well with peer-dep ranges. Workflow:++```bash+pnpm changeset # describe what changed → writes a markdown file+git commit -am "feat: x"+pnpm changeset version # bumps package versions + writes CHANGELOG+pnpm install # resolve workspace versions+git commit -am "Release"+pnpm publish -r # publish updated packages+```++Standalone plugin repos can run Changesets the same way; the CLI scaffold doesn't pre-configure it.++## Publishing the npm package++```bash+pnpm build+pnpm publish --access public+```++Set `"private": false` and remove the `"publishConfig.access": "restricted"` if your scaffold has it.++## Avoiding lock-step releases++Your plugin should compile against a **range** of dashboard versions. Run the build against the lowest supported version locally (`pnpm add -D @spree/[email protected]`) and add a CI matrix job that bumps to the next minor and rebuilds. That's the cheapest way to catch "I depended on something that doesn't exist in 6.0.0".++## Reference++- [npm `peerDependencies` docs](https://docs.npmjs.com/cli/v10/configuring-npm/package-json#peerdependencies)+- [Changesets](https://github.com/changesets/changesets)+- [tsup docs](https://tsup.egoist.dev/)diff --git a/docs/v5/developer/dashboard/plugins/scaffolding.mdx b/docs/v5/developer/dashboard/plugins/scaffolding.mdxnew file mode 100644index 0000000000..ef18d5c36e--- /dev/null+++ b/docs/v5/developer/dashboard/plugins/scaffolding.mdx@@ -0,0 +1,134 @@+---+title: Scaffolding+sidebarTitle: Scaffolding+description: Generate a new dashboard plugin monorepo with `@spree/cli` in one command. Includes TypeScript, biome, tsup, a working example entry-point, and translations.+canonical: "https://spreecommerce.org/docs/developer/dashboard/plugins/scaffolding"+---++`@spree/cli` ships a `plugin new` command that scaffolds the whole plugin monorepo for you. Generated layout:++```+your-plugin/+├── package.json # workspace root+├── pnpm-workspace.yaml+├── LICENSE+├── README.md+├── .gitignore+└── packages/+ └── dashboard/+ ├── package.json # @your-scope/dashboard-your-plugin+ ├── tsconfig.json+ ├── biome.json+ └── src/+ ├── index.tsx # defineDashboardPlugin entry+ ├── client.ts # adminClient request wrappers+ ├── types.ts # plugin-specific TS types+ ├── pages/+ │ └── <name>-list.tsx+ ├── routes/ # TanStack file routes, compiled into the host's typed route tree+ │ └── <name>.index.tsx+ ├── slots/+ │ └── product-<name>-card.tsx+ └── locales/+ └── en.json+```++You get a working "Brands"-style plugin out of the box: nav entry, a list page wired through React Query, a product-detail slot card, and English translations.++## Run it++```bash+npx @spree/cli plugin new my-plugin+```++The CLI prompts for:++- **Plugin name** — slug (kebab-case), used for package names and i18n keys+- **Ruby gem name** — only matters if you later add a Rails engine+- **Module name** — PascalCase, used as the React component prefix (`MyPluginCard`)+- **npm scope** — e.g., `@acme`+- **Author + email** — for `package.json` and `LICENSE`; prefilled from `git config user.name` / `user.email`+- **License** — MIT, Apache-2.0, or BSD-3-Clause (MIT by default); the CLI fills in the standard text++Every prompt has a matching flag:++```bash+npx @spree/cli plugin new my-plugin \+ --ruby-name spree_my_plugin \+ --module-name MyPlugin \+ --npm-scope @acme \+ --author "Ada Lovelace" \+ --author-email "[email protected]" \+ --license MIT \+ --no-install # skip pnpm install+```++For CI and scripted use, `-y` / `--yes` accepts the default for anything the flags leave unanswered — author and email come from your git config, everything else derives from the plugin name:++```bash+npx @spree/cli plugin new my-plugin -y+```++`--force` overwrites an existing directory. `--no-dashboard` skips the dashboard package (Rails-engine-only plugins). `--no-engine` is reserved — engine scaffolding lands later.++## After scaffolding++```bash+cd my-plugin+pnpm install # runs by default unless --no-install+pnpm build+```++You now have a buildable plugin. The next page covers what to put in `package.json` for publishing — but if you're using it internally and importing by path, you can stop here and skip [Publishing](/v5/developer/dashboard/plugins/publishing).++## What the entry-point looks like++`packages/dashboard/src/index.tsx` is where everything starts. The generated version, trimmed:++```tsx+import { defineDashboardPlugin, defineTable, i18n } from '@spree/dashboard-core'+import { PackageIcon } from 'lucide-react'+import en from './locales/en.json'+import { MyPluginCard } from './slots/product-my-plugin-card'++// 1. Translations — merge our keys into the shared bundle.+i18n.addResourceBundle('en', 'translation', en, true, true)++// 2. Declare the table our list page renders with <ResourceTable>.+defineTable('my-plugin', {+ title: i18n.t('admin.my_plugin.table.title'),+ defaultSort: { field: 'name', direction: 'asc' },+ columns: [/* … */],+})++// 3. Registry extensions. Routes are NOT registered here — they ship as+// file routes in src/routes/ (declared via the package.json marker) and+// compile into the host's typed route tree. See the routes guide.+defineDashboardPlugin({+ nav: [{+ key: 'my-plugin',+ label: i18n.t('admin.my_plugin.title'),+ path: '/my-plugin',+ icon: PackageIcon,+ position: 250,+ }],+ slots: {+ 'product.form_sidebar': [{+ id: 'my-plugin-card',+ component: MyPluginCard as never,+ position: 50,+ }],+ },+})+```++That's the whole entry-point. Edit it to register what your plugin needs and remove what it doesn't.++## The example endpoints++The generated `client.ts` calls `adminClient.request()` against `/<name>` (relative to `/api/v3/admin`) — those endpoints don't exist by default. You'd add them on the Rails side (a controller, a model, a serializer) for the plugin to do anything end-to-end. The CLI doesn't scaffold the Rails engine today; for now, write that part by hand using the [backend integration docs](/v5/developer/dashboard/customization/backend).++## Reference++- [`@spree/cli` source](https://github.com/spree/spree/tree/main/packages/cli)+- [Template tree](https://github.com/spree/spree/tree/main/packages/cli/templates/plugin) — what gets copied (`.tt` files are template-substituted)diff --git a/docs/v5/developer/dashboard/public-api.mdx b/docs/v5/developer/dashboard/public-api.mdxnew file mode 100644index 0000000000..954719c888--- /dev/null+++ b/docs/v5/developer/dashboard/public-api.mdx@@ -0,0 +1,242 @@+---+title: Public API+sidebarTitle: Public API+description: Every importable symbol the dashboard exposes — components, hooks, registries, providers, and the SDK client. Treat this as the surface you can safely depend on.+canonical: "https://spreecommerce.org/docs/developer/dashboard/public-api"+---++The dashboard is structured as three packages, each with a documented public surface. **Anything not listed here is internal** — don't import it via `@spree/dashboard-core/src/internal/...`, because we'll move or rename it without a deprecation cycle.++## `@spree/dashboard-core`++Default-import surface for plugins and customizations.++### Plugin facade++```ts+import { defineDashboardPlugin } from '@spree/dashboard-core'+```++Single declarative entry-point for every registry. See [Customization Quickstart](/v5/developer/dashboard/customization/quickstart) for the full shape.++### Registries++```ts+import {+ nav,+ settingsNav,+ // route registry+ pluginRoutes,+ matchPluginRoute,+ usePluginRoutes,+ // slot registry+ registerSlot,+ removeSlot,+ updateSlot,+ useSlotEntries,+ // table registry+ tables,+ // extension fields on built-in forms (hydrate + save with the host form)+ formFields,+ // input components for specific custom field definitions+ customFieldComponents,+} from '@spree/dashboard-core'+```++Each registry exposes `add`/`remove`/`update`-style mutators. See the per-feature pages for examples — form fields and custom field components are covered in the [custom form field recipe](/v5/developer/dashboard/recipes/custom-form-field).++### Components++```ts+import {+ // Page chrome+ PageHeader,+ PageTabs,+ TopBar,+ AppSidebar,+ SettingsSidebar,+ Slot,+ StoreSwitcher,+ // Tables+ ResourceTable,+ TableToolbar,+ BulkActionBar,+ // Form widgets+ StoreDatePicker,+ CountryCombobox,+ CountryStateFields,+ CurrencySelect,+ LocaleSelect,+ MarketCombobox,+ ResourceCombobox,+ ResourceMultiAutocomplete,+ TagCombobox,+ PreferencesForm,+ AddressFormDialog,+ // Permission+ Can,+ // Export+ ExportButton,+} from '@spree/dashboard-core'+```++### Hooks++```ts+import {+ useAuth, // current admin user+ usePermissions, // CanCanCan abilities+ useStore, // current store+ useCommandPalette, // ⌘K palette open/close state+ useGlobalSearch, // global search query state+ useCountries,+ useCustomFields,+ useDirectUpload, // ActiveStorage direct uploads+ useExport, // CSV export job lifecycle+ useResourceMutation, // useMutation wrapper with 422 handling+ useHostForm, // the built-in form a slot widget renders inside (throws when absent)+ useOptionalHostForm, // same, but null when the page has no host form+} from '@spree/dashboard-core'+```++### Helpers++```ts+import {+ filtersToRansack, // converts table filter state → Ransack params+ mapSpreeErrorsToForm, // 422 response → form.setError+ // formatters+ formatPrice, // Price object → display string+ formatStoreDateTime, // ISO string → wall-clock in the store's timezone+ getInitials, // full name → avatar initials+ // i18n+ i18n, // configured instance+ // form mappers — normalize optional text inputs before submitting+ blankToNull,+ blankToUndefined,+} from '@spree/dashboard-core'+```++### SDK client++```ts+import { adminClient } from '@spree/dashboard-core'+```++The shared `@spree/admin-sdk` instance configured for the host's API URL. Use this everywhere instead of constructing your own.++### Providers++```ts+import {+ AuthProvider,+ PermissionProvider,+ StoreProvider,+} from '@spree/dashboard-core'+```++Mount these at the root of your app shell. The shipped app shell does this for you — re-export only if you're composing a custom shell (vendor panel, etc.).++### Vite plugin++```ts+import { spreeDashboardPlugin } from '@spree/dashboard-core/vite'+```++Vite plugin that resolves third-party dashboard plugins and injects Tailwind `@source` directives for their CSS. See [Distributing](/v5/developer/dashboard/plugins/distributing) for the host wiring.++## `@spree/dashboard-ui`++Design system primitives. Headless — accept data via props, never reach for providers or hooks.++### shadcn-style primitives++```ts+import {+ Button,+ Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter,+ Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,+ Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter,+ DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem,+ Input, Textarea, Checkbox, RadioGroup, Switch,+ Select, SelectTrigger, SelectContent, SelectItem, SelectValue,+ Combobox,+ Field, FieldLabel, FieldError, FieldDescription,+ Table, TableHeader, TableBody, TableRow, TableCell,+ Badge,+ Avatar,+ Skeleton,+ Tooltip, TooltipTrigger, TooltipContent,+ Toaster,+} from '@spree/dashboard-ui'+```++Toast *notifications* come from [sonner](https://sonner.emilkowal.ski/) directly — `import { toast } from 'sonner'` — while `<Toaster>` (the mount point, already rendered by the app shell) is the only part re-exported here.++### Composed components++Higher-level pieces that bundle multiple primitives but still take data via props:++```ts+import {+ ResourceLayout, // header + main + sidebar grid+ Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,+ ColorPicker,+ // …more land here as we extract from @spree/dashboard+} from '@spree/dashboard-ui'+```++`Empty*` composes via children (icon in `<EmptyMedia>`, actions in `<EmptyContent>`) rather than taking `title`/`description` props.++### Utilities++```ts+import { cn } from '@spree/dashboard-ui' // clsx + tailwind-merge+```++## `@spree/dashboard`++The app shell. **Plugins don't import from here** — a plugin extends the dashboard through `@spree/dashboard-core` and never renders the shell. The host (the `dashboard-starter` project, or a create-spree-app project) is what imports it, to mount the admin:++```ts+import { createDashboardRouter, Dashboard } from '@spree/dashboard'+```++- **`Dashboard`** — the app shell component (provider stack + router). Render it with a router: `<Dashboard router={router} />`.+- **`createDashboardRouter(routeTree)`** — builds the router from the host's generated `routeTree.gen.ts` (the shell's routes composed with every installed plugin's file routes). The starter's `main.tsx` wires these together; you rarely write this by hand.++Two subpath entries complete the surface:++```ts+import { spreeDashboardPlugin } from '@spree/dashboard/vite' // Vite plugin: Tailwind, discovery, route composition+import '@spree/dashboard/styles.css' // the app's CSS entry+```++Importing from `@spree/dashboard` pins your code to the deployable app's version. Plugins and custom UI should prefer `@spree/dashboard-core` + `@spree/dashboard-ui`.++## What about `@spree/admin-sdk`?++The Admin API client is a separate package and a public dependency. Import types and `SpreeError` from it directly:++```ts+import {+ type Product,+ type Order,+ type Customer,+ SpreeError,+} from '@spree/admin-sdk'+```++The `adminClient` instance, by contrast, comes from `@spree/dashboard-core` so the host owns the configured singleton.++## Stability++Anything on this page is covered by semver from `@spree/dashboard-core` 1.0.0 onward. Pre-1.0 we may rename, but we'll call breaking moves out in the changelog.++Anything not listed here is internal. If you find yourself wanting it, open a discussion — it's a sign we should promote it to the public surface.++## Reference++- [`packages/dashboard-core/src/index.ts`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/index.ts) — canonical export list+- [`packages/dashboard-ui/src/index.ts`](https://github.com/spree/spree/blob/main/packages/dashboard-ui/src/index.ts)+- [`packages/admin-sdk/src/index.ts`](https://github.com/spree/spree/blob/main/packages/admin-sdk/src/index.ts)diff --git a/docs/v5/developer/dashboard/recipes/attribute-end-to-end.mdx b/docs/v5/developer/dashboard/recipes/attribute-end-to-end.mdxnew file mode 100644index 0000000000..cb4a5fd78b--- /dev/null+++ b/docs/v5/developer/dashboard/recipes/attribute-end-to-end.mdx@@ -0,0 +1,214 @@+---+title: "A product attribute, end to end: form, table, filters, sort"+sidebarTitle: Attribute end-to-end+description: Take one custom product attribute all the way — editable on the product form, visible as a table column, filterable and sortable in the products list.+canonical: "https://spreecommerce.org/docs/developer/dashboard/recipes/attribute-end-to-end"+---++This recipe adds a **supplier lead time** (`lead_time_days`, an integer) to products and wires it through every surface the dashboard has:++- edited on the product form, saved by the form's own Save button+- a column in the products table+- a filter ("lead time > 7 days") and a sort ("slowest first") in the list toolbar++It's the full version of the [custom form field recipe](/v5/developer/dashboard/recipes/custom-form-field) — read that one first if you only need the form.++## First: should this be a custom field instead?++**Default to a [custom field definition](/v5/developer/dashboard/recipes/custom-form-field#path-a-custom-field-definition--no-code).** It needs zero code — declare the field, and the product form renders and saves it. That covers most plugin data and everything merchants define themselves.++Graduate to a real database column only when the attribute needs **list operations or database guarantees**:++| You need… | Custom field | Real column |+|---|---|---|+| Editing on the product form | ✅ zero code | ✅ this recipe |+| Filtering / sorting the products list in Admin | ❌ | ✅ via Ransack |+| Merchants defining the field themselves at runtime | ✅ | ❌ |++Lead time is a column because its whole point is the query: *"show me everything that ships slow, slowest first."*++## 1. Backend++Four small pieces — each one unlocks a specific frontend capability. In a host app these live in `backend/` (or `api/`); in a distributed plugin, in the Rails engine half.++**The column** (with an index — you're adding it *because* it will be queried):++```ruby+class AddLeadTimeDaysToSpreeProducts < ActiveRecord::Migration[7.2]+ def change+ add_column :spree_products, :lead_time_days, :integer+ add_index :spree_products, :lead_time_days+ end+end+```++**The serializer** — makes the attribute *readable* (hydrates the form, renders the table cell):++```ruby+# app/serializers/admin/product_serializer.rb+module Admin+ class ProductSerializer < Spree::Api::V3::Admin::ProductSerializer+ attributes :lead_time_days+ end+end++# config/initializers/spree.rb+Spree.api.admin_product_serializer = 'Admin::ProductSerializer'+```++**The permitted param** — makes it *writable* (the form's Save ships it in the same PATCH as core fields). The read and write names must match:++```ruby+# app/controllers/spree/api/v3/admin/products_controller_decorator.rb+module Spree+ module Api+ module V3+ module Admin+ module ProductsControllerDecorator+ def permitted_params+ super.merge(params.permit(:lead_time_days))+ end+ end++ ProductsController.prepend(ProductsControllerDecorator)+ end+ end+ end+end+```++**The Ransack allowlist** — makes it *filterable and sortable*. Both the list's sort param and every filter predicate go through Ransack, and Ransack refuses attributes that aren't allowlisted:++```ruby+# config/initializers/spree.rb+Spree::Product.whitelisted_ransackable_attributes |= %w[lead_time_days]+```++Add a Rails validation while you're here (`validates :lead_time_days, numericality: { greater_than_or_equal_to: 0, allow_nil: true }`) — it's the authoritative validation, and the dashboard renders its 422 message inline on the field automatically.++## 2. Frontend — one declaration++```tsx+// src/plugins.ts (or a plugin's entry module)+import { defineDashboardPlugin, i18n } from '@spree/dashboard-core'+import { LeadTimeCard } from './fields/lead-time-card'+import en from './locales/en.json'++i18n.addResourceBundle('en', 'translation', en, true, true)++defineDashboardPlugin({+ // Form: hydrate from the fetched product, save with the form's own Save.+ formFields: {+ product: [{ name: 'lead_time_days', from: (p) => p?.lead_time_days ?? null }],+ },+ slots: {+ 'product.form_sidebar': [{ id: 'lead-time', component: LeadTimeCard as never, position: 60 }],+ },++ // Table: column + filter + sort in one ColumnDef.+ tables: {+ products: {+ add: [{+ key: 'lead_time_days',+ label: i18n.t('admin.fields.product.lead_time_days.label'),+ sortable: true, // header click → server-side sort via Ransack+ filterable: true, // appears in the filter panel+ filterType: 'number', // numeric operator set: =, ≠, >, <, ranges+ default: true, // visible out of the box (false = opt-in via column picker)+ render: (product) => (product.lead_time_days != null ? `${product.lead_time_days} d` : '—'),+ }],+ },+ },+})+```++The form widget binds to the host form — no `<form>` of its own, no save button:++```tsx+// src/fields/lead-time-card.tsx+import { useHostForm } from '@spree/dashboard-core'+import { Card, CardContent, CardHeader, CardTitle, Field, FieldError, FieldLabel, Input } from '@spree/dashboard-ui'+import { useTranslation } from 'react-i18next'++export function LeadTimeCard() {+ const { t } = useTranslation()+ const form = useHostForm<{ lead_time_days: number | null }>()+ const error = form.formState.errors.lead_time_days?.message++ return (+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.fields.product.lead_time_days.label')}</CardTitle>+ </CardHeader>+ <CardContent>+ <Field>+ <FieldLabel className="sr-only" htmlFor="lead_time_days">+ {t('admin.fields.product.lead_time_days.label')}+ </FieldLabel>+ <Input+ id="lead_time_days"+ type="number"+ min={0}+ placeholder={t('admin.fields.product.lead_time_days.placeholder')}+ aria-invalid={Boolean(error)}+ {...form.register('lead_time_days', {+ // Empty input → null (not NaN, not "") so the API gets a clean value.+ setValueAs: (v) => (v === '' || v == null ? null : Number(v)),+ })}+ />+ {error && <FieldError>{error as string}</FieldError>}+ </Field>+ </CardContent>+ </Card>+ )+}+```++```json+// src/locales/en.json — note the top-level "admin" wrapper+{+ "admin": {+ "fields": {+ "product": {+ "lead_time_days": {+ "label": "Lead time (days)",+ "placeholder": "e.g. 14"+ }+ }+ }+ }+}+```++## 3. Verify it++API first — the fastest way to confirm the backend pieces:++```bash+# write (permitted param + validation)+npx spree api patch products/prod_xxx --data '{"lead_time_days": 14}'++# filter + sort (Ransack allowlist)+npx spree api get "products?q[lead_time_days_gt]=7&sort=-lead_time_days"+```++Then the UI: open a product — the Lead time card sits in the sidebar; edit it and the page's Save button arms; save and reload. On the products list the column renders, the header sorts, and the filter panel offers the numeric operators. Filters and sort round-trip through the URL — a filtered view is shareable — and a CSV export of the filtered list respects your filter, because the export stores the same Ransack predicate hash.++## How the pieces map++| Frontend behavior | Made possible by |+|---|---|+| Form input hydrates + saves with the page | serializer attribute + permitted param + `formFields`/`useHostForm` |+| Table cell renders | serializer attribute + `ColumnDef.render` |+| Header sort works | `sortable: true` + Ransack allowlist |+| Filter panel entry works | `filterable: true` + `filterType` + Ransack allowlist |+| Inline validation message | the Rails validation (422 → mapped onto the field) |++Two `ColumnDef` extras worth knowing: `ransackAttribute` points the predicate somewhere other than the column key (the built-in `sku` column filters through `master_sku`), and `displayable: false` makes a filter-only field that never renders as a column.++## Reference++- [Custom form field recipe](/v5/developer/dashboard/recipes/custom-form-field) — the form layer in isolation, and the custom-field-definition path+- [Tables](/v5/developer/dashboard/customization/tables) — the full `ColumnDef` and table registry API+- [Backend integration](/v5/developer/dashboard/customization/backend) — serializers, permitted params, error mapping+- [Decorators](/v5/developer/customization/decorators) — the `prepend` pattern used for the controllerdiff --git a/docs/v5/developer/dashboard/recipes/custom-form-field.mdx b/docs/v5/developer/dashboard/recipes/custom-form-field.mdxnew file mode 100644index 0000000000..dcaee54064--- /dev/null+++ b/docs/v5/developer/dashboard/recipes/custom-form-field.mdx@@ -0,0 +1,175 @@+---+title: Add a custom field to the product form+sidebarTitle: Custom form field+description: Add a field to the built-in product form that hydrates from the API and saves with the form's own Save button — no save logic of your own.+canonical: "https://spreecommerce.org/docs/developer/dashboard/recipes/custom-form-field"+---++Two ways to get a custom field onto the product form, both saved by the page's single Save button:++- **Custom field definition (no code)** — declare the field as data; the dashboard renders it. Right for merchant-managed attributes and most plugin data.+- **Extension form field (code)** — for a real database column your plugin added to `spree_products`. You register the field and render its input; hydration and saving stay with the host form.++## Path A: custom field definition — no code++Create a definition for products (Settings → Custom fields, the in-place "Set up" button on the Custom Fields card, or the API):++```bash+npx spree api post custom_field_definitions --data '{+ "resource_type": "Spree::Product",+ "namespace": "specs",+ "key": "tech_specs",+ "label": "Technical specifications",+ "field_type": "long_text"+}'+```++That's the whole feature. The **Custom Fields card** on the product form now renders a textarea for it; the value rides the form's `custom_fields[]` and persists when the merchant hits **Save**. Field types: `short_text`, `long_text`, `rich_text`, `number`, `boolean`, `json`.++### Optional: replace the input widget++When the default widget isn't right — a color, a rating, a structured pair — register a component for that specific definition, keyed by its `namespace.key`:++```tsx+// src/plugins.ts (or a plugin's entry module)+import { type CustomFieldComponentProps, defineDashboardPlugin } from '@spree/dashboard-core'++function ColorPicker({ id, value, onChange, ariaLabel }: CustomFieldComponentProps) {+ return (+ <input+ id={id}+ type="color"+ aria-label={ariaLabel}+ value={(value as string) || '#000000'}+ onChange={(e) => onChange(e.target.value)}+ />+ )+}++defineDashboardPlugin({+ customFieldComponents: {+ 'specs.color': ColorPicker,+ },+})+```++The component is a controlled input — render `value`, call `onChange`. Persistence stays with the card (the form's Save on products and categories; the card's own Save on orders and customers). When no component is registered, the default widget for the definition's `field_type` renders.++## Path B: extension form field — a real column++Use this when your plugin adds an actual column and API attribute.++### 1. Backend++```ruby+class AddTechSpecsToSpreeProducts < ActiveRecord::Migration[7.2]+ def change+ add_column :spree_products, :tech_specs, :text, null: false, default: ''+ end+end+```++Expose it on the Admin API — the serializer returns `tech_specs`, and the products controller permits it on write (see [Backend integration](/v5/developer/dashboard/customization/backend)). Read and write names must match.++### 2. Register the field++Tell the product form about the field: where its value comes from on load. Everything else — dirty tracking, the PATCH payload, re-baselining after save — is the host form's job.++```tsx+// src/plugins.ts (or a plugin's entry module)+import { defineDashboardPlugin } from '@spree/dashboard-core'++defineDashboardPlugin({+ formFields: {+ product: [+ // `from` receives the fetched product — or null on the create form.+ { name: 'tech_specs', from: (product) => product?.tech_specs ?? '' },+ ],+ },+})+```++### 3. Render the input from a slot++The `product.form_sidebar` slot renders inside the product form. Bind your input to the host form with `useHostForm()` — no `<form>` of your own, no save button:++```tsx+// src/fields/tech-specs-card.tsx+import { useHostForm } from '@spree/dashboard-core'+import {+ Card, CardContent, CardHeader, CardTitle,+ Field, FieldError, FieldLabel, Textarea,+} from '@spree/dashboard-ui'+import { useTranslation } from 'react-i18next'++export function TechSpecsCard() {+ const { t } = useTranslation()+ const form = useHostForm<{ tech_specs: string }>()+ const error = form.formState.errors.tech_specs?.message++ return (+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.fields.product.tech_specs.label')}</CardTitle>+ </CardHeader>+ <CardContent>+ <Field>+ <FieldLabel className="sr-only" htmlFor="tech_specs">+ {t('admin.fields.product.tech_specs.label')}+ </FieldLabel>+ <Textarea+ id="tech_specs"+ rows={6}+ placeholder={t('admin.fields.product.tech_specs.placeholder')}+ aria-invalid={Boolean(error)}+ {...form.register('tech_specs')}+ />+ {error && <FieldError>{error as string}</FieldError>}+ </Field>+ </CardContent>+ </Card>+ )+}+```++```tsx+// src/plugins.ts — alongside the formFields registration+defineDashboardPlugin({+ formFields: {+ product: [{ name: 'tech_specs', from: (product) => product?.tech_specs ?? '' }],+ },+ slots: {+ 'product.form_sidebar': [{ id: 'tech-specs', component: TechSpecsCard as never, position: 80 }],+ },+})+```++Done. The field hydrates when the page loads, participates in the form's dirty state (Save enables when it changes), ships in the same PATCH as every core field, and re-baselines after save.++### Validation++Extension fields are validated by the **server** — a Rails validation failing returns a 422, and the host form's error mapping puts the message inline on your field (that's the `errors.tech_specs` read in the component). This mirrors how Vendure and Saleor treat extension-field validation: the backend is authoritative; the client renders what it says.++### Which forms support this++`useHostForm()` works wherever a built-in form exposes its form context — currently the **product** (edit + new), **category** (edit + new), and **store settings** forms, with matching slots (`product.form_sidebar`, `category.form_sidebar`, `store.form_main`) and form keys (`product`, `category`, `store`). Orders and customers have no page-wide form — their sheets own their edits — so slot widgets there manage their own persistence; use `useOptionalHostForm()` to write a widget that adapts to both contexts.++## Which path should I pick?++| Situation | Path |+|---|---|+| Merchant-defined attributes, plugin data without schema migrations | **A** — definition, zero code |+| Default widget is fine | **A** |+| A real column with Rails validations, queries, or indexes | **B** |+| The field belongs visually inside your own card with other UI | **B** |++## Going further++To also surface the attribute as a **table column with filtering and sorting**, continue with [A product attribute, end to end](/v5/developer/dashboard/recipes/attribute-end-to-end).++## Reference++- [Custom fields](/v5/developer/customization/metadata) — definitions, types, the API+- [Slots](/v5/developer/dashboard/customization/slots) — the injection mechanism+- [`useHostForm`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/hooks/use-host-form.ts)+- [`formFields` registry](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/form-fields-registry.ts)diff --git a/docs/v5/developer/dashboard/recipes/page-action-button.mdx b/docs/v5/developer/dashboard/recipes/page-action-button.mdxnew file mode 100644index 0000000000..cff6dc7b2e--- /dev/null+++ b/docs/v5/developer/dashboard/recipes/page-action-button.mdx@@ -0,0 +1,190 @@+---+title: Add a page action button+sidebarTitle: Page action button+description: Add a primary action (e.g., "Send invoice", "Sync to ERP") to a built-in detail page's header — both as a top-right button and as a dropdown item.+canonical: "https://spreecommerce.org/docs/developer/dashboard/recipes/page-action-button"+---++Built-in detail pages render `<PageHeader>` at the top with primary action buttons on the right and a more-actions (`⋯`) dropdown next to them. Both are slot-based — you can inject your own buttons or menu items without touching the host page.++Two slots cover the surface:++- `page.actions` — the right-aligned action zone (buttons, badges)+- `page.actions_dropdown` — the dropdown menu++This recipe shows both — and how to gate them by permission + resource state. (Strings are hardcoded for brevity; real buttons should go through i18n — see [Translations](/v5/developer/dashboard/customization/translations).)++## A button in the actions row++```tsx+// src/actions/send-invoice-button.tsx+import { adminClient, usePermissions, useResourceMutation } from '@spree/dashboard-core'+import { Button } from '@spree/dashboard-ui'+import { Send } from 'lucide-react'++interface Props {+ resource: { id: string; state: string } // Order+}++export function SendInvoiceButton({ resource }: Props) {+ const { permissions } = usePermissions()+ const mutation = useResourceMutation({+ mutationFn: () =>+ adminClient.request('POST', `/orders/${resource.id}/send_invoice`),+ successMessage: 'Invoice sent',+ })++ // Only show to users who can act, and only on completed orders.+ if (!permissions.can('update', 'Spree::Order')) return null+ if (resource.state !== 'complete') return null++ return (+ <Button+ variant="outline"+ size="sm"+ onClick={() => mutation.mutate()}+ disabled={mutation.isPending}+ >+ <Send className="size-4" />+ Send invoice+ </Button>+ )+}+```++Register it:++```ts+// src/plugins.ts (in your dashboard app)+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { SendInvoiceButton } from './actions/send-invoice-button'++defineDashboardPlugin({+ slots: {+ 'page.actions': [{+ id: 'send-invoice',+ component: SendInvoiceButton as never,+ position: 50,+ }],+ },+})+```++Two layers of gating, both inside the component:++1. **Permission check** — `usePermissions()`; render `null` when the user can't act.+2. **Resource-state check** — the user *can* send invoices, but this specific order isn't ready yet.++(The slot entry's `if` predicate receives only the slot's own context — `{ resource }` here — so use it for resource-state conditions, and keep permission checks in the component. See [Slots](/v5/developer/dashboard/customization/slots).)++## A dropdown menu item++For secondary actions, use `page.actions_dropdown` and render `<DropdownMenuItem>`:++```tsx+// src/actions/sync-to-erp-item.tsx+import { adminClient, usePermissions, useResourceMutation } from '@spree/dashboard-core'+import { DropdownMenuItem } from '@spree/dashboard-ui'+import { RefreshCw } from 'lucide-react'++interface Props {+ resource: { id: string }+}++export function SyncToErpItem({ resource }: Props) {+ const { permissions } = usePermissions()+ const mutation = useResourceMutation({+ mutationFn: () => adminClient.request('POST', `/orders/${resource.id}/sync_to_erp`),+ successMessage: 'Synced',+ })++ if (!permissions.can('manage', 'Spree::Order')) return null++ return (+ <DropdownMenuItem+ onSelect={(event) => {+ event.preventDefault()+ mutation.mutate()+ }}+ disabled={mutation.isPending}+ >+ <RefreshCw className="size-4" />+ Sync to ERP+ </DropdownMenuItem>+ )+}+```++```ts+defineDashboardPlugin({+ slots: {+ 'page.actions_dropdown': [{+ id: 'sync-to-erp',+ component: SyncToErpItem as never,+ position: 50,+ }],+ },+})+```++The `event.preventDefault()` keeps the dropdown open if the mutation fails — without it, the menu closes on click and the toast appears with no context.++## Confirm before acting++For destructive or expensive actions, wrap the click in a `<Dialog>`:++```tsx+import { useState } from 'react'+import {+ Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,+ DropdownMenuItem, Button,+} from '@spree/dashboard-ui'++export function ResetCartItem({ resource }: { resource: { id: string } }) {+ const [open, setOpen] = useState(false)+ const mutation = useResourceMutation({+ mutationFn: () => adminClient.request('POST', `/orders/${resource.id}/reset_cart`),+ successMessage: 'Cart reset',+ onSuccess: () => setOpen(false),+ })++ return (+ <>+ <DropdownMenuItem+ onSelect={(event) => {+ event.preventDefault()+ setOpen(true)+ }}+ >+ Reset cart+ </DropdownMenuItem>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Reset this cart?</DialogTitle>+ </DialogHeader>+ <p>All line items will be cleared. This cannot be undone.</p>+ <DialogFooter>+ <Button variant="ghost" onClick={() => setOpen(false)}>Cancel</Button>+ <Button variant="destructive" onClick={() => mutation.mutate()}>+ Reset+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ )+}+```++## Context++The `resource` prop is whatever the host page passed to `<PageHeader resource={…} />`. On the order detail page it's an `Order`; on a product page it's a `Product`. The slot doesn't statically know which — see [Slots](/v5/developer/dashboard/customization/slots) for the typing escape hatches.++For the current store, user, or permissions, call the hooks inside your component — `useStore()`, `useAuth()`, `usePermissions()` from `@spree/dashboard-core`.++## Reference++- [`page.actions` / `page.actions_dropdown`](/v5/developer/dashboard/slots-catalog#page-header-slots) in the slots catalog+- [`useResourceMutation`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/hooks/use-resource-mutation.ts) — 422-aware mutation hook+- [Slots](/v5/developer/dashboard/customization/slots) — registry primerdiff --git a/docs/v5/developer/dashboard/recipes/sidebar-widget.mdx b/docs/v5/developer/dashboard/recipes/sidebar-widget.mdxnew file mode 100644index 0000000000..98ed3a2137--- /dev/null+++ b/docs/v5/developer/dashboard/recipes/sidebar-widget.mdx@@ -0,0 +1,148 @@+---+title: Add a sidebar widget+sidebarTitle: Sidebar widget+description: Add an info card to a built-in detail page's sidebar — pulling its own data, gated by permissions, with loading and empty states.+canonical: "https://spreecommerce.org/docs/developer/dashboard/recipes/sidebar-widget"+---++The product, order, and customer detail pages each render a `<Slot>` in their right-hand sidebar — typically named `<resource>.form_sidebar`. Widgets rendered into these slots see the current record and can fetch their own data without disturbing the host page.++This recipe builds a "Loyalty status" card for the customer detail page: read-only, fetches the customer's points + tier, shows a spinner while loading, an empty state when there's no data, and hides itself for staff without the right permission.++## The component++```tsx+// src/widgets/loyalty-status-card.tsx+import { useQuery } from '@tanstack/react-query'+import { adminClient, usePermissions, useStore } from '@spree/dashboard-core'+import {+ Badge,+ Card, CardContent, CardHeader, CardTitle,+ Empty, EmptyDescription,+ Skeleton,+} from '@spree/dashboard-ui'+import { Trophy } from 'lucide-react'++interface LoyaltyRecord {+ customer_id: string+ points: number+ tier: 'bronze' | 'silver' | 'gold'+}++interface Props {+ // The customer detail page's slot context — see the slots catalog.+ customer: { id: string }+}++export function LoyaltyStatusCard({ customer }: Props) {+ const { storeId } = useStore()+ const { permissions } = usePermissions()+ const canRead = permissions.can('read', 'MyApp::LoyaltyRecord')+ const { data, isLoading } = useQuery({+ queryKey: ['loyalty', storeId, customer.id],+ queryFn: () =>+ adminClient.request<{ data: LoyaltyRecord | null }>(+ 'GET',+ `/customers/${customer.id}/loyalty`,+ ),+ staleTime: 30_000,+ enabled: canRead,+ })++ // Hide entirely for staff without the permission — same behavior as+ // core's permission-gated cards.+ if (!canRead) return null++ return (+ <Card>+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ <Trophy className="size-4" />+ Loyalty status+ </CardTitle>+ </CardHeader>+ <CardContent>+ {isLoading ? (+ <Skeleton className="h-8 w-32" />+ ) : !data?.data ? (+ <Empty>+ <EmptyDescription>No loyalty record</EmptyDescription>+ </Empty>+ ) : (+ <div className="space-y-2">+ <Badge variant={tierVariant(data.data.tier)}>{data.data.tier}</Badge>+ <p className="text-sm text-muted-foreground">{data.data.points} points</p>+ </div>+ )}+ </CardContent>+ </Card>+ )+}++function tierVariant(tier: LoyaltyRecord['tier']) {+ return tier === 'gold' ? 'default' : 'secondary'+}+```++Worth noting:++- **`storeId` in the query key.** The dashboard is multi-store; without this, switching stores leaves stale data on screen.+- **`staleTime: 30_000`** keeps the data fresh enough for a sidebar widget without re-fetching on every focus event.+- **Three states.** Loading (`<Skeleton>`), empty (`<Empty>`), and loaded. Skipping the empty state ships a card that says "0 points" when really the customer has never been enrolled — different meaning, different UX.+- **Strings are hardcoded for brevity.** Real widgets should go through i18n — see [Translations](/v5/developer/dashboard/customization/translations).++## Register the widget++```ts+// src/plugins.ts (in your dashboard app)+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { LoyaltyStatusCard } from './widgets/loyalty-status-card'++defineDashboardPlugin({+ slots: {+ 'customer.form_sidebar': [{+ id: 'loyalty-status',+ component: LoyaltyStatusCard as never,+ position: 50,+ }],+ },+})+```++The permission gate lives *inside* the component (`usePermissions`) rather than in an `if` predicate on the entry — the predicate only receives the slot context today, not ambient permissions (see the [slots catalog](/v5/developer/dashboard/slots-catalog#ambient-context)).++`position: 50` puts the card near the top of the sidebar (built-in cards typically use 100/200/300). Pick a number based on whether your widget is more or less important than the others — for a "status" card, near the top is right.++## When to fetch in the widget vs. read from the host++The pattern above fetches its own data. The alternative is to read it from the resource the host passes:++```tsx+function MyCard({ customer }: { customer: Customer }) {+ return <div>{customer.loyalty_points}</div> // host already loaded it+}+```++Choose based on **whether the data is hot path for the rest of the page**:++| Data | Approach |+|---|---|+| Already on the host's serializer (e.g., `customer.tags`) | Read from the slot context — no extra HTTP |+| Conditional, expensive, or owned by your plugin | Fetch in the widget |+| Sometimes-needed (e.g., gated by feature flag) | Fetch in the widget |++A widget that always fetches is wasteful when the host already has the data. A widget that reads from the host but the host doesn't serialize is broken. Match the pattern to the source of truth.++## Loading states for the host page++The built-in detail pages render their sidebar only after the record has loaded, so the context record is always set when your widget mounts. If you register into a slot where that's not guaranteed (check the slots catalog entry), guard defensively:++```tsx+if (!customer) return null // or a <Skeleton> to reserve layout space+```++## Reference++- [Slots catalog → form sidebars](/v5/developer/dashboard/slots-catalog) — every page-level sidebar slot+- [`useQuery`](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) — query key conventions+- [`@spree/dashboard` README](https://github.com/spree/spree/blob/main/packages/dashboard/README.md) — the multi-store model and why `storeId` belongs in the keydiff --git a/docs/v5/developer/dashboard/slots-catalog.mdx b/docs/v5/developer/dashboard/slots-catalog.mdxnew file mode 100644index 0000000000..20d0b22632--- /dev/null+++ b/docs/v5/developer/dashboard/slots-catalog.mdx@@ -0,0 +1,174 @@+---+title: Slots catalog+sidebarTitle: Slots catalog+description: Every named slot the dashboard renders today. Each entry lists the host page, the slot name, and the context the slot's components receive.+canonical: "https://spreecommerce.org/docs/developer/dashboard/slots-catalog"+---++This is the canonical list of slots the dashboard currently exposes. The source of truth is the `<Slot name="…">` call sites in the dashboard source (linked under Reference below); each entry here records the host page, the slot name, and the context your component receives.++If you need a new injection point in a built-in page, open a PR adding `<Slot name="..." context={...} />` and a documentation entry here — that's the contract for new slots.++## Ambient context++Ambient context (`permissions`, `store`, `user` merged into every slot's props) is planned but **not wired up yet** — today slot components receive only the slot-specific context listed below. Until it lands, read those values with the hooks instead:++```tsx+import { usePermissions, useStore } from '@spree/dashboard-core'++function MyWidget({ product }: { product: Product }) {+ const { permissions } = usePermissions()+ const { store } = useStore()+ if (!permissions.can('read', 'MyApp::LoyaltyRecord')) return null+ // ...+}+```++The same applies to an entry's `if` predicate: it receives the slot context, but not `permissions` — gate inside the component for now.++## Page header slots++Rendered by `<PageHeader>` (`@spree/dashboard-core/components/page-header.tsx`) at the top of every detail and list page that uses the shared chrome.++### `page.actions`++| Where | Top-right of `<PageHeader>`, left of any explicit `actions` prop |+|---|---|+| Use | Add primary action buttons (e.g., a "Refund" button on the order detail page) |+| Context | `{ resource, ...slotContext }` — `resource` is the current page's primary record, when the host passed one to `<PageHeader resource={...} />`. May be `undefined` on list pages. |++### `page.actions_dropdown`++| Where | Inside the more-actions (`⋯`) dropdown menu, above the auto-rendered Copy ID / Delete items |+|---|---|+| Use | Add menu items (`<DropdownMenuItem>`) for secondary actions |+| Context | `{ resource, ...slotContext }` — same as `page.actions` |++## Detail-page form slots++The resource detail pages each render a slot below their built-in cards. The context key matches the resource name.++**Host form:** on pages marked *host form: yes*, the slot renders inside the page's own `<form>` and the form context is exposed — widgets can bind inputs via [`useHostForm()`](/v5/developer/dashboard/recipes/custom-form-field) that hydrate, dirty-track, and save with the page's Save button. On pages without one, widgets own their persistence (use `useOptionalHostForm()` to adapt).++### `product.form_sidebar`++| Where | Product detail page (`products/$productId`), end of the sidebar column |+|---|---|+| Use | Add a card scoped to the product being edited (e.g., a "Brand" picker, wishlist stats, sync status from an external system) |+| Context | `{ product }` — the full `Product` record from the Admin API |+| Host form | **Yes** — form key `product` |++### `category.form_sidebar`++| Where | Category detail page (`products/categories/$categoryId`), end of the sidebar column |+|---|---|+| Use | Category-scoped cards — merchandising rules, feed settings, external sync state |+| Context | `{ category }` — the `Category` record (may be briefly `undefined` while refetching) |+| Host form | **Yes** — form key `category` |++### `store.form_main`++| Where | Store settings page (`settings/store`), end of the main column |+|---|---|+| Use | Store-level settings a plugin owns — integration toggles, account linking |+| Context | `{ store }` — the full `Store` record |+| Host form | **Yes** — form key `store` |++### `order.form_sidebar`++| Where | Order detail page (`orders/$orderId`), end of the sidebar column |+|---|---|+| Use | Fraud-check status, shipping-integration state, loyalty points earned |+| Context | `{ order }` — the full `Order` record |+| Host form | No — widgets save via their own API calls |++### `customer.form_sidebar`++| Where | Customer detail page (`customers/$customerId`), end of the sidebar column |+|---|---|+| Use | Loyalty status, support-ticket summary, external CRM links |+| Context | `{ customer }` — the full `Customer` record |+| Host form | No — the page edits through sheets; widgets save via their own API calls |++## Page tabs slot++### `page.tabs` (default)++Rendered by `<PageTabs>` at the right edge of any tabbed sub-nav.++| Where | After the built-in tab strip |+|---|---|+| Use | Append your own tab(s) to a sub-route — typically for plugin-owned views inside an existing resource (e.g., "Returns" tab on the order detail) |+| Context | `{ tabs, ...slotContext }` — `tabs` is the array of built-in tabs (so you can inspect or filter by them) |++Some pages override `slotName` to scope tabs to a single resource (e.g., `slotName="order.tabs"`). The catalog will grow these as we wire them up; today only the default `page.tabs` name is in production use.++## Payment method editor slots (dynamic)++Used by `<PaymentMethodForm>` to let payment-provider plugins replace pieces of the editor sheet. The slot names are computed per provider type (`stripe`, `bogus`, …), so registering against the right name is what hooks your editor in.++### `payment_method.guide.<providerType>`++| Where | Above the preferences form |+|---|---|+| Use | Banner explaining what the integration does, what credentials to use, links to provider docs |+| Context | `PaymentMethodEditorContext` (see below) |++### `payment_method.form.<providerType>`++| Where | In place of the auto-generated preferences form |+|---|---|+| Use | Render a custom React form when the provider's preferences are too complex for the generated UI (multi-step OAuth, environment switchers, …) |+| Context | `PaymentMethodEditorContext` |++### `payment_method.actions.<providerType>`++| Where | Sheet footer, before Save/Cancel |+|---|---|+| Use | Provider-specific action buttons — "Test connection", "Rotate keys", "Open dashboard in provider" |+| Context | `PaymentMethodEditorContext` |++### `PaymentMethodEditorContext`++```ts+interface PaymentMethodEditorContext {+ mode: 'create' | 'edit'+ type: string // STI shorthand (`stripe`, `bogus`, …)+ paymentMethod: PaymentMethod | null // null in create mode+ preferenceSchema: PreferenceField[]+ preferences: Record<string, unknown>+ onPreferencesChange: (next: Record<string, unknown>) => void+ form: UseFormReturn<PaymentMethodFormValues> // RHF instance for top-level fields+}+```++Helpers for building the slot name:++```ts+import {+ paymentMethodGuideSlot,+ paymentMethodFormSlot,+ paymentMethodActionsSlot,+} from '@spree/dashboard/components/spree/payment-method-editors/types'++paymentMethodFormSlot('stripe') // → "payment_method.form.stripe"+```++Use these instead of constructing the string yourself, so a rename in one place doesn't silently break your registration.++## Adding a new slot++If a built-in page should expose a new injection point:++1. Pick a name (`<resource>.<area>`, e.g., `order.timeline`)+2. Add `<Slot name="..." context={{ resource: order, /* ... */ }} />` at the call site+3. Document the slot here — host, intent, context shape+4. Open the PR++The slot is not "live" until the docs land — without an entry here, no plugin author knows it exists.++## Reference++- [`<Slot>` source](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/components/slot.tsx)+- [`slot-registry`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/slot-registry.ts) — `registerSlot`, `removeSlot`, `updateSlot`, `useSlotEntries`+- [Slots customization page](/v5/developer/dashboard/customization/slots) — how to register against a slotdiff --git a/docs/v5/developer/deployment/assets.mdx b/docs/v5/developer/deployment/assets.mdxnew file mode 100644index 0000000000..345b8aa36e--- /dev/null+++ b/docs/v5/developer/deployment/assets.mdx@@ -0,0 +1,92 @@+---+title: Assets+canonical: "https://spreecommerce.org/docs/developer/deployment/assets"+---++By default, files are stored on the local filesystem. For production, use a cloud storage service.++Spree auto-detects the storage provider based on which environment variables are set — no code changes needed. See [Environment Variables](/v5/developer/deployment/environment_variables#file-storage-s3--cloudflare-r2) for the full list.++## AWS S3++Set the following environment variables:++| Variable | Default | Description |+| --- | --- | --- |+| `AWS_ACCESS_KEY_ID` | — | AWS access key |+| `AWS_SECRET_ACCESS_KEY` | — | AWS secret key |+| `AWS_REGION` | — | AWS region (e.g., `us-east-1`) |+| `AWS_BUCKET` | `spree-production` | S3 bucket name |++### CORS Configuration++The Admin Dashboard uses direct uploads. Configure CORS on your S3 bucket to allow this:++1. Go to your S3 bucket in AWS Console+2. Click on "Permissions" tab+3. Scroll down to "Cross-origin resource sharing (CORS)"+4. Click "Edit" and paste the following configuration:++```json+[+ {+ "AllowedMethods": ["GET", "PUT", "POST"],+ "AllowedOrigins": ["https://myspreestore.com"],+ "AllowedHeaders": ["*"],+ "ExposeHeaders": ["ETag"]+ }+]+```++<Info>+Replace `myspreestore.com` with the domain you use to access your Spree Admin Dashboard.+</Info>++## Cloudflare R2++Cloudflare R2 is S3-compatible object storage with zero egress fees and a built-in CDN.++Set the following environment variables:++| Variable | Default | Description |+| --- | --- | --- |+| `CLOUDFLARE_ENDPOINT` | — | R2 endpoint URL |+| `CLOUDFLARE_ACCESS_KEY_ID` | — | R2 access key |+| `CLOUDFLARE_SECRET_ACCESS_KEY` | — | R2 secret key |+| `CLOUDFLARE_BUCKET` | `spree-production` | R2 bucket name |++### CORS Configuration++Configure CORS on your R2 bucket for direct uploads:++1. Go to your R2 bucket in Cloudflare Console+2. Click on "Settings" tab+3. Scroll down to "CORS policy"+4. Click "Edit CORS policy" and paste the following configuration:++```json+[+ {+ "AllowedOrigins": [+ "https://myspreestore.com"+ ],+ "AllowedMethods": [+ "PUT"+ ],+ "AllowedHeaders": [+ "*"+ ],+ "ExposeHeaders": [+ "Origin",+ "Content-Type",+ "Content-MD5",+ "Content-Disposition"+ ],+ "MaxAgeSeconds": 3600+ }+]+```++<Info>+Replace `myspreestore.com` with the domain you use to access your Spree Admin Dashboard.+</Info>diff --git a/docs/v5/developer/deployment/aws.mdx b/docs/v5/developer/deployment/aws.mdxnew file mode 100644index 0000000000..ad41c68e2a--- /dev/null+++ b/docs/v5/developer/deployment/aws.mdx@@ -0,0 +1,110 @@+---+title: AWS — EC2 + RDS+sidebarTitle: EC2 + RDS+description: The simplest production Spree on AWS — one EC2 instance and a managed database.+canonical: "https://spreecommerce.org/docs/developer/deployment/aws"+---++The simplest way to run Spree on AWS is the [single-node topology](/v5/developer/deployment/quickstart#single-node-vs-distributed): **one EC2 instance running the Docker image, one RDS database**. No clusters, no load balancers, no task definitions — a complete production store for roughly the cost of a t3.small and a small RDS instance.++Need auto-scaling, zero-downtime deploys, or CI/CD-driven infrastructure? That's the [ECS Fargate guide](/v5/developer/deployment/aws_ecs) — it runs the same Docker image, so you can start here and graduate later without rework.++## What You'll Create++| Resource | Purpose | Starting size |+|---|---|---|+| **EC2 instance** | Runs the Spree container (web + background jobs) | `t3.small` (2 GB) to start, `t3.medium` for comfort |+| **RDS PostgreSQL** | The only backing service — data, jobs, cache | `db.t4g.small` |+| **DNS record** | Your store's web address, e.g. `store.example.com`, pointing at the instance's Elastic IP (a free static IP — a plain EC2 IP changes on restart and would break the record) | — |+| **S3 bucket** (recommended) | Uploaded files (product images) — they shouldn't live on the instance disk. See [Asset Storage](/v5/developer/deployment/assets) | — |++## 1. Create the Database (RDS)++Create an **RDS PostgreSQL** instance in the AWS console:++- Same VPC as your EC2 instance will use+- **Public access: no** — instead, allow inbound port `5432` from the EC2 instance's security group+- Note the endpoint, username, and password — they become your `DATABASE_URL`++Spree also runs on RDS MySQL/MariaDB and both Aurora flavors — see [Database Configuration](/v5/developer/deployment/database). RDS takes automated daily backups by default, so the database needs no extra care.++## 2. Launch the Instance++Launch an EC2 instance (Ubuntu 24.04 or Amazon Linux 2023) and open ports `80` and `443` in its security group. Give it a stable web address: associate an Elastic IP (so the instance's IP survives restarts) and create a DNS record for your domain — e.g. an `A` record for `store.example.com` — pointing at it. HTTPS depends on this: Caddy can only obtain a certificate once the domain resolves to the instance.++Then install Docker:++```bash+curl -fsSL https://get.docker.com | sh+```++## 3. Run Spree++Build [your project's image](/v5/developer/deployment/docker) and push it to a registry the instance can pull from (ECR or any other) — or use the stock `ghcr.io/spree/spree:latest` image to start. Then create a `docker-compose.yml` on the instance:++```yaml docker-compose.yml+services:+ web:+ image: your-registry/my-store:latest # or ghcr.io/spree/spree:latest+ restart: unless-stopped+ environment:+ DATABASE_URL: postgres://spree:[email protected]:5432/spree_production+ SECRET_KEY_BASE: generate-with-openssl-rand-hex-64+ RAILS_HOST: store.example.com+ # Uploads to S3 (recommended) — see /developer/deployment/assets+ # AWS_REGION: eu-west-1+ # AWS_BUCKET: my-store-uploads+ # AWS_ACCESS_KEY_ID: ...+ # AWS_SECRET_ACCESS_KEY: ...+ # Email delivery — see /developer/deployment/emails+ # SMTP_HOST: smtp.resend.com+ # SMTP_USERNAME: resend+ # SMTP_PASSWORD: ...+ # SMTP_FROM_ADDRESS: [email protected]++ # Caddy terminates HTTPS with an automatic Let's Encrypt certificate+ caddy:+ image: caddy:2+ restart: unless-stopped+ ports:+ - "80:80"+ - "443:443"+ command: caddy reverse-proxy --from store.example.com --to web:3000+ volumes:+ - caddy_data:/data++volumes:+ caddy_data:+```++```bash+docker compose up -d+```++The database is migrated automatically on boot. Once DNS resolves, your store is live at `https://store.example.com` — admin at `/admin`, background jobs running inside the web container ([combined mode](/v5/developer/deployment/quickstart#web-and-worker)).++## Updating++Deploying a new version is a pull and a restart:++```bash+docker compose pull && docker compose up -d+```++This restarts the container with a few seconds of downtime — the point at which that matters is a good signal to consider [ECS Fargate](/v5/developer/deployment/aws_ecs) and its rolling deploys.++## Scaling on One Box++Before reaching for a cluster:++- **Bigger instance** — a `t3.medium` or `t3.large` carries substantial traffic; resizing is a stop/start+- **Split the worker** — add a second service to the compose file with `command: bin/jobs`, and set `SOLID_QUEUE_IN_PUMA: "false"` on `web` ([split mode](/v5/developer/deployment/quickstart#web-and-worker))+- **Scale the database** — RDS resizes independently, and read replicas are a console click++## Next Steps++- [Asset Storage](/v5/developer/deployment/assets) — store uploads in S3+- [Set environment variables](/v5/developer/deployment/environment_variables) — SMTP, Sentry, etc.+- [Configure CDN](/v5/developer/deployment/cdn) — CloudFront in front of your assets+- [Deploy the storefront](/v5/developer/storefront/nextjs/deployment) — the Next.js storefront ships separately, typically to Vercel+- [ECS Fargate](/v5/developer/deployment/aws_ecs) — when you outgrow one boxdiff --git a/docs/v5/developer/deployment/aws_ecs.mdx b/docs/v5/developer/deployment/aws_ecs.mdxnew file mode 100644index 0000000000..4efcce5bd7--- /dev/null+++ b/docs/v5/developer/deployment/aws_ecs.mdx@@ -0,0 +1,463 @@+---+title: AWS — ECS Fargate+sidebarTitle: ECS Fargate+description: Production-grade Spree on AWS — ECS Fargate, RDS, CI/CD, and auto-scaling.+canonical: "https://spreecommerce.org/docs/developer/deployment/aws_ecs"+---++This is the advanced AWS path: containers managed by ECS Fargate with auto-scaling, zero-downtime rolling deploys, CI/CD via GitHub Actions, and secrets in AWS Secrets Manager. If you're getting started or running a single store, the [EC2 + RDS guide](/v5/developer/deployment/aws) gets you to production with a fraction of the moving parts — on the same [Docker image](/v5/developer/deployment/docker), so you can graduate to ECS later without rework.++## Required AWS Services++The required set is smaller than an AWS architecture diagram suggests — four services run the store:++| Service | Purpose |+|---------|---------|+| [ECS Fargate](https://aws.amazon.com/fargate/) | Runs the web (and optional worker) containers — no servers to manage |+| [RDS](https://aws.amazon.com/rds/) | The database — data, background jobs, and cache all live here. PostgreSQL, MySQL/MariaDB, and both Aurora flavors work — see [Database Configuration](/v5/developer/deployment/database) |+| [ECR](https://aws.amazon.com/ecr/) | Registry for your Docker image |+| [S3](https://aws.amazon.com/s3/) | Uploaded files (product images) — Fargate containers have no persistent disk. See [Asset Storage](/v5/developer/deployment/assets#aws-s3) |++In front of the web service you'll put an **Application Load Balancer** with a free HTTPS certificate from [Certificate Manager](https://aws.amazon.com/certificate-manager/) — that's your public entry point.++Everything else is optional:++| Service | When |+|---------|------|+| [CloudFront](https://aws.amazon.com/cloudfront/) | [CDN](/v5/developer/deployment/cdn) in front of assets and images |+| [ElastiCache](https://aws.amazon.com/elasticache/) | Valkey/Redis for [high-traffic caching](/v5/developer/deployment/caching) — the default cache lives in the database |+| [Route 53](https://aws.amazon.com/route53/) | DNS — convenient on AWS, but any DNS provider works |++## Docker Image++Build [your project's image](/v5/developer/deployment/docker) with `spree build --production`, or use the stock `ghcr.io/spree/spree` image for deployments without customizations.++To build and deploy a custom image to AWS ECR via GitHub Actions:++```yaml+name: Deploy to AWS Fargate++on:+ push:+ branches: [ main ]+ pull_request:+ branches: [ main ]++env:+ AWS_REGION: us-east-1+ ECR_REPOSITORY: spree-starter+ ECS_SERVICE_WEB: spree-web+ ECS_SERVICE_WORKER: spree-worker+ ECS_CLUSTER: spree-cluster++jobs:+ build:+ name: Build and Push to ECR+ runs-on: ubuntu-latest++ outputs:+ image: ${{ steps.build-image.outputs.image }}+ image-tag: ${{ steps.build-image.outputs.image-tag }}++ steps:+ - name: Checkout code+ uses: actions/checkout@v4++ - name: Configure AWS credentials+ uses: aws-actions/configure-aws-credentials@v4+ with:+ aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}+ aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}+ aws-region: ${{ env.AWS_REGION }}++ - name: Login to Amazon ECR+ id: login-ecr+ uses: aws-actions/amazon-ecr-login@v2++ - name: Build, tag, and push image to Amazon ECR+ id: build-image+ env:+ ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}+ IMAGE_TAG: ${{ github.sha }}+ run: |+ # Build a docker container and push it to ECR+ docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .+ docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG+ echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" >> $GITHUB_OUTPUT+ echo "image-tag=$IMAGE_TAG" >> $GITHUB_OUTPUT++ deploy-web:+ name: Deploy Web Service+ runs-on: ubuntu-latest+ needs: build+ if: github.ref == 'refs/heads/main'++ steps:+ - name: Checkout code+ uses: actions/checkout@v4++ - name: Configure AWS credentials+ uses: aws-actions/configure-aws-credentials@v4+ with:+ aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}+ aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}+ aws-region: ${{ env.AWS_REGION }}++ - name: Fill in the new image ID in the Amazon ECS task definition+ id: task-def-web+ uses: aws-actions/amazon-ecs-render-task-definition@v1+ env:+ ECR_REGISTRY: ${{ needs.build.outputs.image }}+ IMAGE_TAG: ${{ needs.build.outputs.image-tag }}+ AWS_ACCOUNT_ID: ${{ secrets.AWS_ACCOUNT_ID }}+ with:+ task-definition: .aws/web-task-definition.json+ container-name: web+ image: ${{ needs.build.outputs.image }}++ - name: Deploy Amazon ECS task definition for web+ uses: aws-actions/amazon-ecs-deploy-task-definition@v1+ with:+ task-definition: ${{ steps.task-def-web.outputs.task-definition }}+ service: ${{ env.ECS_SERVICE_WEB }}+ cluster: ${{ env.ECS_CLUSTER }}+ wait-for-service-stability: true++ deploy-worker:+ name: Deploy Worker Service+ runs-on: ubuntu-latest+ needs: build+ if: github.ref == 'refs/heads/main'++ steps:+ - name: Checkout code+ uses: actions/checkout@v4++ - name: Configure AWS credentials+ uses: aws-actions/configure-aws-credentials@v4+ with:+ aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}+ aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}+ aws-region: ${{ env.AWS_REGION }}++ - name: Fill in the new image ID in the Amazon ECS task definition+ id: task-def-worker+ uses: aws-actions/amazon-ecs-render-task-definition@v1+ env:+ ECR_REGISTRY: ${{ needs.build.outputs.image }}+ IMAGE_TAG: ${{ needs.build.outputs.image-tag }}+ AWS_ACCOUNT_ID: ${{ secrets.AWS_ACCOUNT_ID }}+ with:+ task-definition: .aws/worker-task-definition.json+ container-name: worker+ image: ${{ needs.build.outputs.image }}++ - name: Deploy Amazon ECS task definition for worker+ uses: aws-actions/amazon-ecs-deploy-task-definition@v1+ with:+ task-definition: ${{ steps.task-def-worker.outputs.task-definition }}+ service: ${{ env.ECS_SERVICE_WORKER }}+ cluster: ${{ env.ECS_CLUSTER }}+ wait-for-service-stability: true++ migrate:+ name: Run Database Migrations+ runs-on: ubuntu-latest+ needs: [build, deploy-web]+ if: github.ref == 'refs/heads/main'++ steps:+ - name: Checkout code+ uses: actions/checkout@v4++ - name: Configure AWS credentials+ uses: aws-actions/configure-aws-credentials@v4+ with:+ aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}+ aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}+ aws-region: ${{ env.AWS_REGION }}++ - name: Run database migrations+ run: |+ aws ecs run-task \+ --cluster ${{ env.ECS_CLUSTER }} \+ --task-definition spree-web \+ --overrides '{+ "containerOverrides": [{+ "name": "web",+ "command": ["bundle", "exec", "rails", "db:migrate"]+ }]+ }' \+ --launch-type FARGATE \+ --network-configuration '{+ "awsvpcConfiguration": {+ "subnets": ["'${{ secrets.SUBNET_ID_1 }}'", "'${{ secrets.SUBNET_ID_2 }}'"],+ "securityGroups": ["'${{ secrets.SECURITY_GROUP_ID }}'"],+ "assignPublicIp": "ENABLED"+ }+ }'+```++This action requires secrets to be set in your GitHub repository. You can find the full list of secrets in the [AWS ECS Deploy Task Definition](https://github.com/aws-actions/amazon-ecs-deploy-task-definition) GitHub Actions repository.++| Secret | Description |+|--------|-------------|+| `AWS_ACCESS_KEY_ID` | AWS access key ID |+| `AWS_SECRET_ACCESS_KEY` | AWS secret access key |+| `AWS_ACCOUNT_ID` | AWS account ID |+| `SUBNET_ID_1` | First subnet ID |+| `SUBNET_ID_2` | Second subnet ID |+| `SECURITY_GROUP_ID` | Security group ID |++## Environment Variables++Store secrets in [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/) and reference them in your task definitions. Non-sensitive configuration goes in the `environment` array directly.++For a full list of available variables, see [Environment Variables](/v5/developer/deployment/environment_variables).++### Secrets Manager++Create the following secrets in AWS Secrets Manager:++| Secret Name | Variable | Description |+|---|---|---|+| `spree/database-url` | `DATABASE_URL` | PostgreSQL connection URL |+| `spree/secret-key-base` | `SECRET_KEY_BASE` | Generate with `bin/rails secret` |++Optional secrets for email delivery, file storage, and error tracking:++| Secret Name | Variable | Description |+|---|---|---|+| `spree/smtp-password` | `SMTP_PASSWORD` | SMTP auth password |+| `spree/sentry-dsn` | `SENTRY_DSN` | Sentry DSN for error tracking |++<Tip>+ S3 file storage credentials are not needed as environment variables when your ECS task role has the appropriate S3 permissions. Use IAM roles instead of access keys when possible.+</Tip>++## ECS Task Definitions++One task definition runs the whole app — the web server also runs background jobs in-process ([combined mode](/v5/developer/deployment/quickstart#web-and-worker)). Save it as `.aws/web-task-definition.json`. The worker task definition is an optional scale-out step — skip it (and the `deploy-worker` job in the workflow above) until job load deserves its own service.++### Web Service++```json+{+ "family": "spree-web",+ "networkMode": "awsvpc",+ "requiresCompatibilities": ["FARGATE"],+ "cpu": "1024",+ "memory": "4096",+ "executionRoleArn": "arn:aws:iam::${AWS_ACCOUNT_ID}:role/ecsTaskExecutionRole",+ "taskRoleArn": "arn:aws:iam::${AWS_ACCOUNT_ID}:role/ecsTaskRole",+ "containerDefinitions": [+ {+ "name": "web",+ "image": "${ECR_REGISTRY}/${ECR_REPOSITORY}:${IMAGE_TAG}",+ "portMappings": [+ {+ "containerPort": 3000,+ "protocol": "tcp"+ }+ ],+ "essential": true,+ "environment": [+ {+ "name": "RAILS_ENV",+ "value": "production"+ },+ {+ "name": "PORT",+ "value": "3000"+ },+ {+ "name": "RAILS_MAX_THREADS",+ "value": "3"+ },+ {+ "name": "WEB_CONCURRENCY",+ "value": "auto"+ },+ {+ "name": "RAILS_LOG_LEVEL",+ "value": "info"+ },+ {+ "name": "AWS_BUCKET",+ "value": "your-spree-bucket"+ }+ ],+ "secrets": [+ {+ "name": "DATABASE_URL",+ "valueFrom": "arn:aws:secretsmanager:${AWS_REGION}:${AWS_ACCOUNT_ID}:secret:spree/database-url"+ },+ {+ "name": "SECRET_KEY_BASE",+ "valueFrom": "arn:aws:secretsmanager:${AWS_REGION}:${AWS_ACCOUNT_ID}:secret:spree/secret-key-base"+ }+ ],+ "logConfiguration": {+ "logDriver": "awslogs",+ "options": {+ "awslogs-group": "/ecs/spree-web",+ "awslogs-region": "${AWS_REGION}",+ "awslogs-stream-prefix": "ecs"+ }+ },+ "healthCheck": {+ "command": ["CMD-SHELL", "curl -f http://localhost:3000/up || exit 1"],+ "interval": 30,+ "timeout": 5,+ "retries": 3,+ "startPeriod": 60+ }+ }+ ]+}+```++### Worker Service (optional scale-out)++Switches to [split mode](/v5/developer/deployment/quickstart#web-and-worker): background jobs move into a dedicated service — same image, no rebuild. When you deploy it, set `SOLID_QUEUE_IN_PUMA=false` in the web task's `environment` so the web container stops running jobs. Save as `.aws/worker-task-definition.json`:++```json+{+ "family": "spree-worker",+ "networkMode": "awsvpc",+ "requiresCompatibilities": ["FARGATE"],+ "cpu": "512",+ "memory": "2048",+ "executionRoleArn": "arn:aws:iam::${AWS_ACCOUNT_ID}:role/ecsTaskExecutionRole",+ "taskRoleArn": "arn:aws:iam::${AWS_ACCOUNT_ID}:role/ecsTaskRole",+ "containerDefinitions": [+ {+ "name": "worker",+ "image": "${ECR_REGISTRY}/${ECR_REPOSITORY}:${IMAGE_TAG}",+ "command": ["bin/jobs"],+ "essential": true,+ "environment": [+ {+ "name": "RAILS_ENV",+ "value": "production"+ },+ {+ "name": "RAILS_LOG_LEVEL",+ "value": "info"+ }+ ],+ "secrets": [+ {+ "name": "DATABASE_URL",+ "valueFrom": "arn:aws:secretsmanager:${AWS_REGION}:${AWS_ACCOUNT_ID}:secret:spree/database-url"+ },+ {+ "name": "SECRET_KEY_BASE",+ "valueFrom": "arn:aws:secretsmanager:${AWS_REGION}:${AWS_ACCOUNT_ID}:secret:spree/secret-key-base"+ }+ ],+ "logConfiguration": {+ "logDriver": "awslogs",+ "options": {+ "awslogs-group": "/ecs/spree-worker",+ "awslogs-region": "${AWS_REGION}",+ "awslogs-stream-prefix": "ecs"+ }+ },+ "healthCheck": {+ "command": ["CMD-SHELL", "pgrep -f solid_queue || exit 1"],+ "interval": 30,+ "timeout": 5,+ "retries": 3,+ "startPeriod": 60+ }+ }+ ]+}+```++## Production Sizing++The task definitions above are sized for production. Here is a summary and scaling guidance:++| Service | Fargate CPU | Fargate Memory | Instances |+|---|---|---|---|+| **Web** | 1 vCPU | 4 GB | 2+ (use ECS Service Auto Scaling) |+| **Worker** (optional split) | 0.5 vCPU | 2 GB | 1+ |+| **RDS (PostgreSQL)** | — | `db.r6g.large` (2 vCPU, 16 GB) | 1 |++The database also stores background jobs and cache — the sizing above accounts for it. Scaling the web service to multiple instances is safe with in-process jobs: instances coordinate through the database. Add ElastiCache (Valkey or Redis) only for [high-traffic caching](/v5/developer/deployment/caching).++### Auto Scaling++Use [ECS Service Auto Scaling](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-auto-scaling.html) to scale the web service based on CPU or memory utilization:++```bash+# Register a scalable target (min 2, max 6 tasks)+aws application-autoscaling register-scalable-target \+ --service-namespace ecs \+ --resource-id service/spree-cluster/spree-web \+ --scalable-dimension ecs:service:DesiredCount \+ --min-capacity 2 \+ --max-capacity 6++# Scale based on average CPU utilization (target 70%)+aws application-autoscaling put-scaling-policy \+ --service-namespace ecs \+ --resource-id service/spree-cluster/spree-web \+ --scalable-dimension ecs:service:DesiredCount \+ --policy-name spree-web-cpu-scaling \+ --policy-type TargetTrackingScaling \+ --target-tracking-scaling-policy-configuration '{+ "TargetValue": 70.0,+ "PredefinedMetricSpecification": {+ "PredefinedMetricType": "ECSServiceAverageCPUUtilization"+ },+ "ScaleInCooldown": 300,+ "ScaleOutCooldown": 60+ }'+```++## After Deployment++### Admin++Access your admin panel at:++```+https://<your-domain>/admin+```++Default credentials are created during `db:seed`. Change them immediately after first login.++### Database Migrations++The GitHub Actions workflow above runs migrations automatically on deploy. To run migrations manually:++```bash+aws ecs run-task \+ --cluster spree-cluster \+ --task-definition spree-web \+ --overrides '{+ "containerOverrides": [{+ "name": "web",+ "command": ["bundle", "exec", "rails", "db:migrate"]+ }]+ }' \+ --launch-type FARGATE \+ --network-configuration '{+ "awsvpcConfiguration": {+ "subnets": ["subnet-xxx", "subnet-yyy"],+ "securityGroups": ["sg-xxx"],+ "assignPublicIp": "DISABLED"+ }+ }'+```++## Next Steps++- [Asset Storage](/v5/developer/deployment/assets) — configure S3 for product images and uploads+- [Configure CDN](/v5/developer/deployment/cdn) — set up CloudFront for asset delivery+- [Configure caching](/v5/developer/deployment/caching) — works out of the box; add ElastiCache for high-traffic installs+- [Set environment variables](/v5/developer/deployment/environment_variables) — SMTP, Sentry, SSL, etc.+- [Deploy the storefront](/v5/developer/storefront/nextjs/deployment) — the Next.js storefront ships separately, typically to Verceldiff --git a/docs/v5/developer/deployment/background_jobs.mdx b/docs/v5/developer/deployment/background_jobs.mdxnew file mode 100644index 0000000000..f1492294b5--- /dev/null+++ b/docs/v5/developer/deployment/background_jobs.mdx@@ -0,0 +1,107 @@+---+title: Background Jobs+description: Spree's background jobs live in your database by default (Solid Queue) — nothing extra to run, with a Sidekiq/Redis swap for very high volume.+canonical: "https://spreecommerce.org/docs/developer/deployment/background_jobs"+---++Everything that doesn't happen during a request runs as a background job: sending emails, processing images, delivering webhooks, importing and exporting catalogs, releasing expired stock reservations. Spree uses Active Job (Rails' standard job interface), so the queue backend is swappable — but the default needs nothing beyond your database.++## Solid Queue — the default++Production uses [Solid Queue](https://github.com/rails/solid_queue) — the built-in background job processor: jobs are stored in your database alongside everything else. There is nothing extra to provision, and by default the job supervisor runs **inside the web container** — one container is the whole application ([combined mode](/v5/developer/deployment/quickstart#web-and-worker)).++When job volume grows, switch to split mode: run a dedicated worker from the same image with `bin/jobs`, and set `SOLID_QUEUE_IN_PUMA=false` on the web service. Multiple web instances and multiple workers are safe by default — they coordinate through the database.++| Variable | Default | Description |+|---|---|---|+| `SOLID_QUEUE_IN_PUMA` | `true` | Run jobs inside the web container; set `false` when a dedicated worker runs |+| `JOB_THREADS` | `3` | Worker thread count — raise it on a dedicated worker |+| `JOB_CONCURRENCY` | `1` | Worker process count — the scaling knob for dedicated workers |++## Job Dashboard++Every deployment ships [Mission Control](https://github.com/rails/mission_control-jobs) — a web UI for background jobs — at `/jobs`: inspect, retry, and discard jobs from the browser. It's guarded by HTTP Basic auth: set `MISSION_CONTROL_USER` and `MISSION_CONTROL_PASSWORD` in production (without them the dashboard stays locked).++## Recurring Jobs++Scheduled work — releasing expired stock reservations, pruning price history, queue housekeeping — is defined in `config/recurring.yml`, Solid Queue's built-in cron. Add your own:++```yaml config/recurring.yml+production:+ nightly_report:+ class: MyReportJob+ schedule: at 5am every day+```++## Queues++`config/queue.yml` lists queues in polling order: checkout-critical and operator-facing work first, bulk catalog processing second, housekeeping last. A trailing `"*"` catches any queue added later. Large CSV imports are additionally capped so they can't occupy the whole worker pool — see [`SPREE_IMPORT_JOB_CONCURRENCY`](/v5/developer/deployment/environment_variables).++## Swapping to Sidekiq++For very high job volume, Spree works with [Sidekiq](https://sidekiq.org/) on Redis or Valkey — like any Active Job backend. This is a bigger step than the [cache swap](/v5/developer/deployment/caching); here is the full setup.++Add the gems and switch the adapter:++```ruby+# Gemfile+gem "sidekiq"+gem "sidekiq-cron" # recurring jobs (replaces config/recurring.yml)+gem "sentry-sidekiq" # only if you use Sentry++# config/application.rb+config.active_job.queue_adapter = :sidekiq+```++Configure the queues with weights — Sidekiq's equivalent of Solid Queue's polling order (checkout-critical work first, bulk catalog processing second, housekeeping last):++```yaml config/sidekiq.yml+:concurrency: <%= Integer(ENV.fetch('SIDEKIQ_CONCURRENCY', '10')) %>+:queues:+ - [default, 5]+ - [spree_imports, 5]+ - [spree_payment_webhooks, 5]+ - [mailers, 5]+ - [spree_events, 3]+ - [spree_exports, 3]+ - [spree_images, 3]+ - [spree_products, 3]+ - [spree_reports, 3]+ - [spree_variants, 3]+ - [spree_taxons, 3]+ - [spree_stock_location_stock_items, 3]+ - [spree_coupon_codes, 3]+ - [spree_addresses, 3]+ - [spree_gift_cards, 3]+ - [spree_webhooks, 3]+ - [spree_api_keys, 3]+ - [spree_search, 3]+ - [active_storage_transform, 3]+ - [active_storage_analysis, 1]+ - [active_storage_purge, 1]+```++Move the `config/recurring.yml` schedules to sidekiq-cron (it auto-loads `config/schedule.yml`):++```yaml config/schedule.yml+expire_stock_reservations:+ cron: "* * * * *"+ class: Spree::StockReservations::ExpireJob+```++The `/jobs` dashboard is Solid Queue-specific — mount [Sidekiq's Web UI](https://github.com/sidekiq/sidekiq/wiki/Monitoring) instead:++```ruby+# config/routes.rb+require "sidekiq/web"++Sidekiq::Web.use Rack::Auth::Basic do |user, password|+ ActiveSupport::SecurityUtils.secure_compare(user, ENV["SIDEKIQ_USER"].to_s) &+ ActiveSupport::SecurityUtils.secure_compare(password, ENV["SIDEKIQ_PASSWORD"].to_s)+end+mount Sidekiq::Web => "/sidekiq"+```++Finally: point Sidekiq at your Redis/Valkey via `REDIS_URL`, run `bundle exec sidekiq` as a dedicated worker service (set `RAILS_MAX_THREADS` to at least `SIDEKIQ_CONCURRENCY` there so the database pool covers every worker thread), and remove the `SOLID_QUEUE_IN_PUMA` setting — with Sidekiq, web and worker are always separate processes.++Reach for this when a dedicated Solid Queue worker with raised `JOB_THREADS`/`JOB_CONCURRENCY` no longer keeps up — for most stores, that point never arrives.diff --git a/docs/v5/developer/deployment/caching.mdx b/docs/v5/developer/deployment/caching.mdxnew file mode 100644index 0000000000..b44ea8e180--- /dev/null+++ b/docs/v5/developer/deployment/caching.mdx@@ -0,0 +1,43 @@+---+title: Caching+description: Spree's cache lives in Postgres by default (Solid Cache) — nothing extra to run, with a one-line Redis/Valkey swap for high-traffic installs.+canonical: "https://spreecommerce.org/docs/developer/deployment/caching"+---++Caching improves performance by storing the results of expensive computations. Spree's headless API caches sparingly — small memoized values (geo data, settings, taxonomy lookups) and the API's rate-limit counters — so the default store needs no dedicated service.++## Solid Cache — the default++Production uses [Solid Cache](https://github.com/rails/solid_cache) — the built-in cache store: the cache lives in your PostgreSQL database alongside everything else. There is nothing to configure, provision, or monitor — it works out of the box in every deployment.++## Swapping to Redis or Valkey++For high-traffic installs that want an in-memory cache, the swap is one line in `config/environments/production.rb` plus the gem:++```ruby+# Gemfile+gem "redis"++# config/environments/production.rb+config.cache_store = :redis_cache_store, { url: ENV["REDIS_URL"] }+```++Works identically with Redis or Valkey (the Linux Foundation fork most hosting platforms now provision).++## Testing Locally++To enable caching in the development environment:++<CodeGroup>++```bash Spree CLI (Docker)+spree rails dev:cache+```++```bash Without Spree CLI+bin/rails dev:cache+```++</CodeGroup>++You will need to restart your web server after this.diff --git a/docs/v5/developer/deployment/cdn.mdx b/docs/v5/developer/deployment/cdn.mdxnew file mode 100644index 0000000000..1be2b393a5--- /dev/null+++ b/docs/v5/developer/deployment/cdn.mdx@@ -0,0 +1,50 @@+---+title: CDN+description: >-+ Learn how to improve performance of your Spree application by using a CDN (Content Delivery Network).+canonical: "https://spreecommerce.org/docs/developer/deployment/cdn"+---++To improve performance of your Spree application, we recommend using a CDN (Content Delivery Network) to cache images and static files.++We recommend using [Cloudflare](https://www.cloudflare.com/) as your CDN provider. It's free and simple to set up.++After setting up your Cloudflare account and adding your domain name to Cloudflare, you will need to set your cache settings.++Go to your domain name in Cloudflare and click on "Caching" tab and select "Cache Rules".++++Click on "Create Rule" and set up the rule as below:++++Supply the first value with++```url+/rails/active_storage/representations/+```++and the second value with++```url+/assets+```++This will handle caching of both images and static files such as JavaScript and CSS files.++Now scroll down and set the settings as below:++++Finally, click on "Deploy" and you are done!++## Dedicated CDN Host++The setup above caches on your primary domain and needs no extra configuration. If you instead serve assets and images from a separate CDN hostname (e.g. a CloudFront or Fastly distribution at `cdn.example.com` with your app as the origin), set the `CDN_HOST` environment variable:++```bash+CDN_HOST=cdn.example.com+```++Static asset URLs and image/attachment URLs (including those in API responses) will then use this host instead of [`RAILS_HOST`](/v5/developer/deployment/environment_variables#urls-and-hosts). Host only, no protocol — URLs keep the scheme of your primary host.\ No newline at end of filediff --git a/docs/v5/developer/deployment/database.mdx b/docs/v5/developer/deployment/database.mdxnew file mode 100644index 0000000000..46acfef48d--- /dev/null+++ b/docs/v5/developer/deployment/database.mdx@@ -0,0 +1,155 @@+---+title: Database Configuration+description: Learn how to configure Spree to work with PostgreSQL, MySQL, or SQLite.+canonical: "https://spreecommerce.org/docs/developer/deployment/database"+---++## Supported Databases++| Database | Development | Production | Notes |+|----------|:-----------:|:----------:|-------|+| **PostgreSQL** | Yes | Yes | Recommended for production. Best performance for large catalogs and high traffic |+| **MySQL** | Yes | Yes | Fully supported. A great choice if your team already uses MySQL |+| **SQLite** | Yes | Yes | Zero-configuration setup. Ideal for development, small stores, and getting started quickly |++## Configuring Your Database++### Using DATABASE_URL++The simplest way to configure your database is via the `DATABASE_URL` environment variable:++```bash+# PostgreSQL+DATABASE_URL=postgres://user:pass@localhost:5432/spree++# MySQL+DATABASE_URL=mysql2://user:pass@localhost:3306/spree++# SQLite+DATABASE_URL=sqlite3:db/production.sqlite3+```++### Using database.yml++You can also configure the database in `config/database.yml`. The connection pool is sized to cover web request threads plus [background job](/v5/developer/deployment/background_jobs) threads, since jobs run inside the web container by default:++<Tabs>+ <Tab title="PostgreSQL">+ ```yaml+ default: &default+ adapter: postgresql+ encoding: unicode+ pool: <%= Integer(ENV.fetch("RAILS_MAX_THREADS", 3)) + Integer(ENV.fetch("JOB_THREADS", 3)) + 3 %>++ development:+ <<: *default+ database: spree_development++ production:+ <<: *default+ database: spree_production+ url: <%= ENV["DATABASE_URL"] %>+ ```+ </Tab>+ <Tab title="MySQL">+ ```yaml+ default: &default+ adapter: mysql2+ encoding: utf8mb4+ pool: <%= Integer(ENV.fetch("RAILS_MAX_THREADS", 3)) + Integer(ENV.fetch("JOB_THREADS", 3)) + 3 %>++ development:+ <<: *default+ database: spree_development++ production:+ <<: *default+ database: spree_production+ url: <%= ENV["DATABASE_URL"] %>+ ```+ </Tab>+ <Tab title="SQLite">+ ```yaml+ default: &default+ adapter: sqlite3+ pool: <%= Integer(ENV.fetch("RAILS_MAX_THREADS", 3)) + Integer(ENV.fetch("JOB_THREADS", 3)) + 3 %>+ timeout: 5000++ development:+ <<: *default+ database: db/development.sqlite3++ production:+ <<: *default+ database: db/production.sqlite3+ ```+ </Tab>+</Tabs>++## Switching Databases++The easiest way to switch your existing Spree application to a different database is using the built-in Rails command:++```bash+# Switch to PostgreSQL+bin/rails db:system:change --to=postgresql++# Switch to MySQL+bin/rails db:system:change --to=mysql++# Switch to SQLite+bin/rails db:system:change --to=sqlite3+```++This command will:+- Update your `Gemfile` with the correct database gem+- Generate a new `config/database.yml` configured for the selected database++After running the command, complete the switch:++1. Install the new gem:++ ```bash+ bundle install+ ```++2. Create the new database and run migrations:++ ```bash+ bin/rails db:create db:migrate+ ```++3. Optionally load sample data:++ ```bash+ bin/rails spree_sample:load+ ```++## Creating a New App with a Specific Database++When creating a new Spree application with the manual installation method, pass the `-d` flag to `rails new`:++```bash+# PostgreSQL+rails new my_store -d postgresql -m https://raw.githubusercontent.com/spree/spree/main/spree/template.rb++# MySQL+rails new my_store -d mysql -m https://raw.githubusercontent.com/spree/spree/main/spree/template.rb++# SQLite (default, no flag needed)+rails new my_store -m https://raw.githubusercontent.com/spree/spree/main/spree/template.rb+```++## Cloud Database Services++For production deployments, you can use managed database services:++| Provider | PostgreSQL | MySQL |+|----------|-----------|-------|+| **AWS** | RDS PostgreSQL, Aurora PostgreSQL | RDS MySQL, Aurora MySQL, RDS MariaDB |+| **Google Cloud** | Cloud SQL for PostgreSQL | Cloud SQL for MySQL |+| **Azure** | Azure Database for PostgreSQL | Azure Database for MySQL |+| **Heroku** | Heroku Postgres | JawsDB, ClearDB |+| **Render** | Render PostgreSQL | — |++Set the `DATABASE_URL` environment variable to the connection string provided by your cloud provider.diff --git a/docs/v5/developer/deployment/docker.mdx b/docs/v5/developer/deployment/docker.mdxnew file mode 100644index 0000000000..1e3a52e3ec--- /dev/null+++ b/docs/v5/developer/deployment/docker.mdx@@ -0,0 +1,126 @@+---+title: Docker+description: Build a production Docker image of your Spree project, or run the official prebuilt image.+canonical: "https://spreecommerce.org/docs/developer/deployment/docker"+---++## Building Your Project's Image++Every [create-spree-app](/v5/developer/create-spree-app/quickstart) project builds into a single production image: the web server and background jobs run in one container, and the only dependency is a PostgreSQL database (the [single-node topology](/v5/developer/deployment/quickstart#single-node-vs-distributed)).++If you haven't ejected yet, do that first:++```bash+spree eject+```++This generates the app source — including its production `Dockerfile` — in `backend/`. Make your customizations, then build:++```bash+spree build --production # → <project>-spree:latest+spree build --production --tag registry.example.com/my-store:v42+```++Or with plain Docker, from the project root:++```bash+docker build . -f backend/Dockerfile -t my-store+```++Both produce the same image — and it's exactly what Render and Railway build from your repository. Migrations run automatically on boot.++## Running the Image++One app container plus Postgres is a complete deployment:++```yaml docker-compose.yml+services:+ postgres:+ image: postgres:18-alpine+ environment:+ POSTGRES_HOST_AUTH_METHOD: trust+ volumes:+ - postgres_data:/var/lib/postgresql/data+ healthcheck:+ test: pg_isready -U postgres+ interval: 5s+ timeout: 5s+ retries: 5++ web:+ image: my-store # or ghcr.io/spree/spree:latest for the stock image+ depends_on:+ postgres:+ condition: service_healthy+ environment:+ DATABASE_URL: postgres://postgres@postgres:5432/spree_production+ SECRET_KEY_BASE: change-me-to-a-real-secret+ RAILS_FORCE_SSL: "false"+ RAILS_ASSUME_SSL: "false"+ # Public host used in generated URLs (images/attachments in API+ # responses, email links) — set to your domain or IP in production.+ RAILS_HOST: localhost:3000+ ports:+ - "3000:3000"+ healthcheck:+ test: curl -f http://localhost:3000/up || exit 1+ interval: 10s+ timeout: 5s+ retries: 10+ start_period: 30s++volumes:+ postgres_data:+```++Start everything:++```bash+docker compose up -d+```++The database is created and migrated on first boot. The app is available at [http://localhost:3000](http://localhost:3000).++### Scaling out the worker++Background jobs run inside the web container by default. When job load deserves its own process, split it out — same image, no rebuild: set `SOLID_QUEUE_IN_PUMA: "false"` on `web` and add a worker service:++```yaml+ worker:+ image: my-store+ depends_on:+ postgres:+ condition: service_healthy+ environment:+ DATABASE_URL: postgres://postgres@postgres:5432/spree_production+ SECRET_KEY_BASE: change-me-to-a-real-secret+ RAILS_HOST: localhost:3000+ command: bin/jobs+```++### Required Environment Variables++| Variable | Description | Example |+| --- | --- | --- |+| `DATABASE_URL` | PostgreSQL connection URL | `postgres://user:pass@host:5432/spree` |+| `SECRET_KEY_BASE` | Secret key for session encryption | Generate with `bin/rails secret` |+| `RAILS_HOST` | Public host used in generated URLs — image/attachment URLs in API responses, email links | `store.example.com` |+| `SOLID_QUEUE_IN_PUMA` | Run background jobs inside the web container (default `true`); set `false` when running a dedicated worker | `true` |++See [Environment Variables](/v5/developer/deployment/environment_variables) for the full list.++## Official Docker Image++To run Spree without any customizations, pull the prebuilt multi-arch image (`linux/amd64` and `linux/arm64`) published to the GitHub Container Registry on every release:++```bash+docker pull ghcr.io/spree/spree:latest+```++| Tag | Description |+|-----|-------------|+| `latest` | Latest stable release |+| `5.4.0` | Specific version |+| `5.4` | Latest patch for a minor version |++Browse all tags on the [GitHub Packages page](https://github.com/spree/spree/pkgs/container/spree). The image drops into the compose file above in place of your custom tag.diff --git a/docs/v5/developer/deployment/emails.mdx b/docs/v5/developer/deployment/emails.mdxnew file mode 100644index 0000000000..484e9384f0--- /dev/null+++ b/docs/v5/developer/deployment/emails.mdx@@ -0,0 +1,159 @@+---+title: Sending out Emails+sidebarTitle: Emails+description: Learn how to send transactional emails from your Spree application.+canonical: "https://spreecommerce.org/docs/developer/deployment/emails"+---++Spree handles two categories of emails:++| Category | Sent by | Examples |+|----------|---------|----------|+| **Customer-facing** | Spree by default; optionally your storefront (via webhooks) | Order confirmation, shipping notification, password reset |+| **System/admin** | Spree | Staff invitation, report ready, export complete |++## Customer-Facing Emails++By default, **Spree sends all customer transactional emails itself** — the `spree_emails` gem ships installed in every deployment. This works for every client of the API: mobile apps, custom frontends, POS integrations — no storefront required. Delivery uses the same [SMTP configuration](#configuration) as system emails.++Customer emails can be turned off in the admin under **Settings → Emails** — do this when your storefront takes over sending them (below), otherwise customers receive both.++### Sending from the Storefront Instead++With the Next.js storefront, you can let the storefront own the customer email experience: the Spree backend publishes webhook events, and the storefront receives them, renders React email templates, and sends via [Resend](https://resend.com) (or any provider).++```+Spree Backend → Webhook POST → Storefront → render email → send via Resend+ (HMAC signed) (verified) (react-email)+```++#### Setup++1. **Create a webhook endpoint** in Spree Admin → Settings → Developers → Webhooks:+ - **URL:** `https://your-storefront.com/api/webhooks/spree`+ - **Events:** `order.completed`, `order.canceled`, `order.shipped`, `customer.password_reset_requested`, `newsletter_subscriber.subscription_requested`++2. **Configure the storefront** with the webhook secret and email provider:++ ```env+ # .env.local (storefront)+ SPREE_WEBHOOK_SECRET=your_webhook_endpoint_secret_key+ RESEND_API_KEY=re_your_resend_api_key+ EMAIL_FROM=Your Store <[email protected]>+ ```++3. **The storefront handles everything else** — signature verification, event routing, email rendering, and delivery are built in. See the [Next.js storefront email docs](/v5/developer/storefront/nextjs/customization#transactional-emails) for template customization.++4. **Turn off Spree's own customer emails** under **Settings → Emails** in the admin, so customers don't receive duplicates.++#### Supported Events++| Event | Email |+|-------|-------|+| `order.completed` | Order confirmation with items, totals, addresses |+| `order.canceled` | Cancellation notice |+| `order.shipped` | Shipping notification with tracking link |+| `customer.password_reset_requested` | Password reset link |+| `newsletter_subscriber.subscription_requested` | Newsletter double opt-in confirmation link |++#### Custom Frameworks++If you're not using the Next.js storefront, you can build your own webhook handler with any framework. Use `@spree/sdk/webhooks` for signature verification:++```typescript+import { verifyWebhookSignature } from '@spree/sdk/webhooks'+```++See [Webhooks documentation](/v5/developer/core-concepts/webhooks) for the full payload format and verification details.++## System Emails++System emails are internal notifications sent to **store staff**, not customers. They are always sent by Spree itself and can't be taken over by a storefront.++| Email | When |+|-------|------|+| Staff invitation | Admin invites a new team member |+| Invitation accepted | Invited user accepts |+| Report ready | Background report generation completes |+| Export complete | Data export finishes |+| Webhook endpoint disabled | Endpoint auto-disabled after repeated failures |++### Configuration++Set the following environment variables on the **Spree backend** to enable email delivery — this configuration powers both customer transactional emails and system emails:++| Variable | Default | Description |+| --- | --- | --- |+| `SMTP_HOST` | — | SMTP server address (e.g., `smtp.sendgrid.net`, `smtp.resend.com`) |+| `SMTP_PORT` | `587` | SMTP server port |+| `SMTP_USERNAME` | — | SMTP auth username |+| `SMTP_PASSWORD` | — | SMTP auth password |+| `SMTP_FROM_ADDRESS` | — | Default "from" email address (e.g., `[email protected]`) |+| `RAILS_HOST` | `example.com` | Public host used in email links and other [generated URLs](/v5/developer/deployment/environment_variables#urls-and-hosts) — image/attachment URLs use `CDN_HOST` instead when set |++When `SMTP_HOST` is not set, emails are printed to the Rails log instead of being sent.++### Provider Examples++<Tabs>+ <Tab title="SendGrid">+ ```bash+ SMTP_HOST=smtp.sendgrid.net+ SMTP_USERNAME=apikey+ SMTP_PASSWORD=SG.your-sendgrid-api-key+ ```++ <Warning>+ Remember to verify the email address in SendGrid you intend to use for sending, otherwise emails will be rejected.+ [Read more about sender verification](https://www.twilio.com/docs/sendgrid/ui/sending-email/sender-verification).+ </Warning>+ </Tab>+ <Tab title="Resend">+ ```bash+ SMTP_HOST=smtp.resend.com+ SMTP_USERNAME=resend+ SMTP_PASSWORD=re_your-resend-api-key+ ```+ </Tab>+ <Tab title="Postmark">+ ```bash+ SMTP_HOST=smtp.postmarkapp.com+ SMTP_USERNAME=your-postmark-server-token+ SMTP_PASSWORD=your-postmark-server-token+ ```+ </Tab>+ <Tab title="Amazon SES">+ ```bash+ SMTP_HOST=email-smtp.us-east-1.amazonaws.com+ SMTP_USERNAME=your-ses-access-key-id+ SMTP_PASSWORD=your-ses-secret-access-key+ ```+ </Tab>+</Tabs>++## Local Development++### Storefront-sent emails++In development, no email provider is needed. Emails are rendered to HTML files in `.next/emails/` with a clickable `file://` link in the console. To preview and design templates:++```bash+npm run email:dev+```++To test the full webhook flow locally, use [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/):++```bash+brew install cloudflared+cloudflared tunnel --url http://localhost:3001+```++Use the tunnel URL as the webhook endpoint URL in Spree Admin.++### Spree-sent emails++In development, all emails Spree sends (customer and system alike) are captured by [Mailpit](https://mailpit.axllent.org/) — nothing is delivered externally. Open **http://localhost:8025** to read them. To deliver through a real provider instead, set `SMTP_HOST` (and friends) in `.env`.diff --git a/docs/v5/developer/deployment/environment_variables.mdx b/docs/v5/developer/deployment/environment_variables.mdxnew file mode 100644index 0000000000..a12dadfdb3--- /dev/null+++ b/docs/v5/developer/deployment/environment_variables.mdx@@ -0,0 +1,153 @@+---+title: Environment Variables+description: Reference for Spree deployment environment variables — database, web server, background jobs, SMTP, file storage, and application settings.+canonical: "https://spreecommerce.org/docs/developer/deployment/environment_variables"+---++Spree uses environment variables for all deployment configuration. No secrets or credentials are stored in the codebase.++## Required++These two variables are all a production deployment strictly needs:++| Variable | Description | Example |+| --- | --- | --- |+| `DATABASE_URL` | Database connection URL — see [Database Configuration](/v5/developer/deployment/database) | `postgres://user:pass@localhost:5432/spree` |+| `SECRET_KEY_BASE` | Secret used to encrypt sessions and cookies. Generate with `openssl rand -hex 64` | `2fad5c0b79d25e4765d3018d8c740f8c3a665f0e5c...` |++You'll almost always want to set [`RAILS_HOST`](#urls-and-hosts) too — without it, generated URLs point at `localhost`.++## URLs and Hosts++`RAILS_HOST` is the canonical public host of your deployment. URLs Spree generates outside a request context use it — links in emails, webhook payloads, and image/attachment URLs in API responses (for the latter, `CDN_HOST` takes precedence when set).++<Warning>+When neither `RAILS_HOST` nor `CDN_HOST` is configured, image and attachment URLs fall back to the store's URL setting, which is `localhost` on a fresh install — API responses will contain `https://localhost/...` URLs.+</Warning>++| Variable | Default | Description |+| --- | --- | --- |+| `RAILS_HOST` | — | Public host, optionally with a port — e.g. `store.example.com` or `203.0.113.7:8080`. Host only, no protocol. On [Render](/v5/developer/deployment/render), falls back to the platform-provided `RENDER_EXTERNAL_HOSTNAME`. |+| `CDN_HOST` | — | Optional host for serving static assets and images, e.g. a CDN distribution in front of your app — see [CDN](/v5/developer/deployment/cdn). Host only, no protocol. Falls back to `RAILS_HOST`. |++Generated URLs use `https` unless both `RAILS_FORCE_SSL` and `RAILS_ASSUME_SSL` are set to `false` (see [SSL](#ssl)).++## Web Server++| Variable | Default | Description |+| --- | --- | --- |+| `PORT` | `3000` | Port the web server listens on |+| `RAILS_MAX_THREADS` | `3` | Concurrent requests each web server process handles |+| `WEB_CONCURRENCY` | `1` | Number of web server processes per container. Set to `auto` for one per CPU core — each process needs roughly 1 GB of RAM |++## Background Jobs++Background jobs (emails, image processing, webhooks, imports) run inside the web container by default — no extra service needed. See [Background Jobs](/v5/developer/deployment/background_jobs) for how this works and when to split out a dedicated worker.++| Variable | Default | Description |+| --- | --- | --- |+| `SOLID_QUEUE_IN_PUMA` | `true` | Run background jobs inside the web container. Set to `false` when you run a dedicated worker service (`bin/jobs`) |+| `JOB_THREADS` | `3` | How many background jobs run concurrently. Raise it on a dedicated worker; the database connection pool sizes itself from this |+| `JOB_CONCURRENCY` | `1` | Number of worker processes — the scaling knob for a dedicated worker |+| `SPREE_IMPORT_JOB_CONCURRENCY` | 75% of `JOB_THREADS` | How much of the job capacity a single CSV import may occupy, so imports can't starve other work. `0` removes the cap |+| `MISSION_CONTROL_USER` / `MISSION_CONTROL_PASSWORD` | — | Login for the `/jobs` dashboard (HTTP Basic auth). Required in production — the dashboard stays locked without them |++## Email (SMTP)++<Tip>+This configuration powers all emails Spree sends — customer transactional emails (order confirmation, shipping notification; on by default) and staff notifications. A storefront can optionally take over customer emails via webhooks — see [Emails](/v5/developer/deployment/emails).+</Tip>++Spree works with any SMTP provider (Resend, Postmark, Mailgun, SendGrid, Amazon SES, etc.). Set `SMTP_HOST` to enable email delivery — when not set, production email delivery is disabled (in development, emails are captured by Mailpit at `http://localhost:8025` instead of being sent). See [Emails](/v5/developer/deployment/emails) for the full guide.++| Variable | Default | Description |+| --- | --- | --- |+| `SMTP_HOST` | — | SMTP server address (e.g., `smtp.sendgrid.net`) |+| `SMTP_PORT` | `587` | SMTP server port |+| `SMTP_USERNAME` | — | SMTP auth username |+| `SMTP_PASSWORD` | — | SMTP auth password |+| `SMTP_FROM_ADDRESS` | — | Default "from" email address |++Links in emails use the host configured via [`RAILS_HOST`](#urls-and-hosts).++## Application++| Variable | Default | Description |+| --- | --- | --- |+| `RAILS_ENV` | `production` | Runtime environment — leave as `production` when deploying |+| `RAILS_LOG_LEVEL` | `info` | Log level (`debug`, `info`, `warn`, `error`) |++## File Storage (S3 / Cloudflare R2)++By default, uploaded files (product images, assets) are stored on the local filesystem. Set the appropriate credentials to use cloud storage instead — Spree auto-detects the provider based on which credentials are present. See [Asset Storage](/v5/developer/deployment/assets) for the full guide.++### Amazon S3++| Variable | Default | Description |+| --- | --- | --- |+| `AWS_ACCESS_KEY_ID` | — | AWS access key |+| `AWS_SECRET_ACCESS_KEY` | — | AWS secret key |+| `AWS_REGION` | — | AWS region (e.g., `us-east-1`) |+| `AWS_BUCKET` | `spree-production` | S3 bucket name |++### Cloudflare R2++| Variable | Default | Description |+| --- | --- | --- |+| `CLOUDFLARE_ENDPOINT` | — | R2 endpoint URL |+| `CLOUDFLARE_ACCESS_KEY_ID` | — | R2 access key |+| `CLOUDFLARE_SECRET_ACCESS_KEY` | — | R2 secret key |+| `CLOUDFLARE_BUCKET` | `spree-production` | R2 bucket name |++## Search (Meilisearch)++Optional. When configured, Spree uses [Meilisearch](/integrations/search/meilisearch) for product search, filtering, and faceted navigation instead of SQL.++| Variable | Default | Description |+| --- | --- | --- |+| `MEILISEARCH_URL` | `http://localhost:7700` | Meilisearch server URL |+| `MEILISEARCH_API_KEY` | — | Meilisearch master key. Not needed for local development — only required when Meilisearch is started with `MEILI_MASTER_KEY`. |++After setting these, enable the provider and reindex:++```ruby+# config/initializers/spree.rb+Spree.search_provider = 'Spree::SearchProvider::Meilisearch'+```++<CodeGroup>++```bash Spree CLI (Docker)+spree rake spree:search:reindex+```++```bash Without Spree CLI+bundle exec rake spree:search:reindex+```++</CodeGroup>++## Error Tracking (Sentry)++| Variable | Default | Description |+| --- | --- | --- |+| `SENTRY_DSN` | — | [Sentry](https://sentry.io/) DSN. When set, errors are reported to Sentry |++## SSL++By default, Spree assumes it runs behind an SSL-terminating reverse proxy or load balancer. Set these to `false` if running without SSL (e.g., local development or behind a proxy that doesn't do SSL termination).++| Variable | Default | Description |+| --- | --- | --- |+| `RAILS_ASSUME_SSL` | `true` | Treat incoming requests as arriving over HTTPS (trust the proxy's forwarded headers) |+| `RAILS_FORCE_SSL` | `true` | Redirect HTTP to HTTPS and use secure cookies |++## Local Development++These variables are used when running the `server/` app locally (not via `DATABASE_URL`):++| Variable | Default | Description |+| --- | --- | --- |+| `DATABASE_HOST` | `localhost` | PostgreSQL host |+| `DATABASE_PORT` | `5432` | PostgreSQL port |+| `DATABASE_USERNAME` | `postgres` | PostgreSQL user |diff --git a/docs/v5/developer/deployment/quickstart.mdx b/docs/v5/developer/deployment/quickstart.mdxnew file mode 100644index 0000000000..f4f6909a5e--- /dev/null+++ b/docs/v5/developer/deployment/quickstart.mdx@@ -0,0 +1,86 @@+---+title: Deployment Overview+sidebarTitle: Quickstart+description: Run Spree anywhere — any cloud, any database, from a single container to a globally distributed stack.+canonical: "https://spreecommerce.org/docs/developer/deployment/quickstart"+---++Spree is open source and self-hosted: you own the entire stack, end to end. There is no proprietary software in the runtime, no required third-party service, and no per-order fees. The same application runs on a $10 VPS, a managed cloud platform, a Kubernetes cluster, or a server in your own data center — and moving between them is a redeploy, not a migration.++## Run It Anywhere++Spree ships as a standard [Docker image](/v5/developer/deployment/docker), which means it runs wherever containers run:++- **Public cloud** — AWS, Google Cloud, Azure, or any provider with container hosting+- **Platform-as-a-Service** — Render, Railway, Fly.io, and similar platforms; deploy from your repository with a Blueprint or a few clicks+- **VPS or bare metal** — a single machine with Docker installed is a complete production environment+- **Kubernetes** — the image is stateless and horizontally scalable, so it drops into any cluster+- **On-premise and intranet** — Spree has no phone-home dependencies, so it runs in private networks and air-gapped environments where SaaS commerce platforms simply can't++The minimum footprint is deliberately small: **one application container and one database**. Background jobs, caching, and real-time updates all run inside that container and store their data in the database — no Redis, no message broker, no extra services to provision or monitor. A store starts comfortably on 1 GB of RAM.++When you need more, every piece scales independently: add web instances behind a load balancer, split job processing into dedicated workers, add a read replica, swap the cache to Redis or Valkey, add Meilisearch for search. Each step is configuration, not rearchitecting.++## Any Database++Spree runs on all major relational databases, including the managed and serverless flavors cloud providers offer:++| Database | Managed options |+|----------|-----------------|+| **PostgreSQL** (recommended) | Amazon RDS, Aurora PostgreSQL, Google Cloud SQL, Azure Database, Neon, Supabase |+| **MySQL / MariaDB** | Amazon RDS, Aurora MySQL, Google Cloud SQL, Azure Database |+| **SQLite** | ideal for development, evaluation, and small stores |++See [Database Configuration](/v5/developer/deployment/database) for details.++## Web and Worker++A Spree deployment has two kinds of work: serving requests (the **web** process) and everything that happens in the background — sending emails, processing images, delivering webhooks, importing catalogs (the **worker**).++You can run them in two modes:++- **Combined (the default)** — the web container also processes background jobs. One container is the whole application. This is how every fresh deployment starts, and it comfortably serves most stores.+- **Split** — when job volume grows, move background processing into a dedicated worker service. It's the same docker image with a different start command and one environment variable (`SOLID_QUEUE_IN_PUMA=false` on web) — no rebuild, no code changes. Recommended for high volume retailers, multi-tenant apps and marketplaces with a lot of vendors using our Shopify sync.++Jobs live in the database, so scaling to multiple web instances or multiple workers is safe by default — they coordinate through it. For demanding workloads, you can also [swap the job backend to Sidekiq](/v5/developer/deployment/background_jobs#swapping-to-sidekiq) on Redis or Valkey. See [Background Jobs](/v5/developer/deployment/background_jobs) for the full picture.++## Single-Node vs Distributed++Spree is API-first, which gives you a real choice of shape:++**Single-node** — one container serves the API, the admin dashboard, and background jobs, with one database behind it. Simplest to operate, cheapest to run, and what [create-spree-app](/v5/developer/create-spree-app/quickstart) projects deploy by default. For headless setups with a mobile app or a custom frontend, this is often all the infrastructure you ever need.++**Distributed** — because the storefront and admin talk to Spree exclusively through its APIs, each surface can be deployed and scaled on its own:++- The **API** scales horizontally behind a load balancer+- The **admin dashboard** is a static React app that can be served from the API container or any static host+- **Workers** scale independently of web traffic+- The **storefront** (Next.js) deploys to Vercel or any Node.js host, rendering at the edge close to your customers++You don't choose upfront. Start single-node, and split surfaces out when traffic or team structure calls for it — the API boundary is already there. Storefront is fully optional, you can use our Next.js reference implementation, or build your own with any framework, build a mobile app, or even a native desktop app. Spree is the backend for all of them.++## Storefront Deployment++The Next.js storefront is a separate application with its own deployment lifecycle — typically on Vercel, but any Node.js host or Docker environment works. It connects to your Spree API with a publishable key and can be redeployed independently of the backend.++See [Storefront Deployment](/v5/developer/storefront/nextjs/deployment) for the full guide.++## Provider Guides++Step-by-step guides for specific platforms:++<CardGroup cols={2}>+ <Card title="AWS" icon="aws" href="/developer/deployment/aws">+ A single EC2 instance + RDS to start, or ECS Fargate with CI/CD and auto-scaling — same image, either way.+ </Card>++ <Card title="Render" icon="server" href="/developer/deployment/render">+ One-click Blueprint: a Docker web service and managed PostgreSQL, built straight from your repository.+ </Card>++ <Card title="Railway (coming soon)">+ A one-click Railway template is on the way.+ </Card>+</CardGroup>++For any other platform, the [Docker guide](/v5/developer/deployment/docker) covers building and running your project's image — which is all any container host needs.diff --git a/docs/v5/developer/deployment/render.mdx b/docs/v5/developer/deployment/render.mdxnew file mode 100644index 0000000000..057116540a--- /dev/null+++ b/docs/v5/developer/deployment/render.mdx@@ -0,0 +1,86 @@+---+title: Render+description: Deploy your Spree project to Render — one Docker service, one Postgres.+canonical: "https://spreecommerce.org/docs/developer/deployment/render"+---++## Overview++Every [create-spree-app](/v5/developer/create-spree-app/quickstart) project ships a ready Render Blueprint (`render.yaml` at the project root). It deploys the whole app in the [single-node topology](/v5/developer/deployment/quickstart#single-node-vs-distributed): **one Docker service built straight from your repository** plus a managed PostgreSQL — nothing else:++- **Web** — one container running the Spree API and background jobs+- **PostgreSQL** — the only backing service++Migrations run automatically on boot. Render builds the same image `spree build --production` builds locally.++<Tip>+Just evaluating Spree? Skip self-hosting entirely and use a hosted sandbox at [spreecommerce.org](https://spreecommerce.org).+</Tip>++## Deploying++1. Push your create-spree-app project to GitHub+2. In the Render dashboard, click **New** → **Blueprint** and select your repository+3. Render reads `render.yaml` and creates the services. Review and click **Deploy Blueprint**.++The database is seeded on first boot. Your store is ready in a few minutes — including any customizations, since the image builds from your repository.++## After Deployment++### Admin++```+https://<your-app-name>.onrender.com/admin # admin panel+https://<your-app-name>.onrender.com/jobs # background jobs dashboard+```++Default credentials are created during seeding. Change them immediately after first login.++The `/jobs` dashboard uses HTTP Basic auth: user `jobs`, with a password the Blueprint generates — read it in the Render dashboard under the web service's **Environment** tab (`MISSION_CONTROL_PASSWORD`).++### Environment Variables++Render sets `DATABASE_URL` and `SECRET_KEY_BASE` automatically from the Blueprint. For additional configuration (SMTP, file storage, Sentry, etc.), see [Environment Variables](/v5/developer/deployment/environment_variables).++Generated URLs (images and attachments in API responses, email links) automatically use Render's `RENDER_EXTERNAL_HOSTNAME` (`<your-app-name>.onrender.com`). When you attach a custom domain, set [`RAILS_HOST`](/v5/developer/deployment/environment_variables#urls-and-hosts) to it — it takes precedence.++## Scaling Out++The Blueprint's commented **worker** block switches to [split mode](/v5/developer/deployment/quickstart#web-and-worker): background jobs move into a dedicated service — same image, no rebuild. Uncomment it and set `SOLID_QUEUE_IN_PUMA=false` on the web service so it stops running jobs.++For production workloads, we recommend:++| Service | Plan | Resources | Auto-scaling |+|---|---|---|---|+| **Web** | Pro | 4 GB RAM, 2 CPU | 1–2 instances |+| **Worker** (optional split) | Standard | 2 GB RAM, 1 CPU | — |+| **PostgreSQL** | Pro 4 GB | 4 GB RAM, 1 CPU | — |++To enable auto-scaling, add this to the web service in your `render.yaml`:++```yaml+- type: web+ name: spree+ plan: pro+ scaling:+ minInstances: 2+ maxInstances: 3+ targetMemoryPercent: 80+ targetCPUPercent: 80+```++High-traffic installs can additionally swap [caching](/v5/developer/deployment/caching) to a managed Redis/Valkey — the default needs no extra service.++## Next Steps++Render provides ephemeral storage — uploaded files (product images, etc.) won't persist across deploys. Set up cloud storage:++- [Asset Storage](/v5/developer/deployment/assets) (Amazon S3 / Cloudflare R2)++Before going to production:++- [Set environment variables](/v5/developer/deployment/environment_variables) (SMTP, SSL, etc.)+- [Configure CDN](/v5/developer/deployment/cdn)+- [Configure caching](/v5/developer/deployment/caching)++Deploying a storefront? The Next.js storefront ships separately — typically to Vercel. See [Storefront Deployment](/v5/developer/storefront/nextjs/deployment).diff --git a/docs/developer/deployment/telemetry.mdx b/docs/v5/developer/deployment/telemetry.mdxsimilarity index 99%rename from docs/developer/deployment/telemetry.mdxrename to docs/v5/developer/deployment/telemetry.mdxindex a7d6ed5392..77e1b41072 100644--- a/docs/developer/deployment/telemetry.mdx+++ b/docs/v5/developer/deployment/telemetry.mdx@@ -1,6 +1,7 @@---title: Telemetrydescription: Distributed tracing with OpenTelemetry — one gem, standard OTEL_* environment variables, and every checkout becomes a trace from HTTP request to gateway call to webhook delivery.+canonical: "https://spreecommerce.org/docs/v5/developer/deployment/telemetry"---Spree supports [OpenTelemetry](https://opentelemetry.io), the open standard fordiff --git a/docs/v5/developer/getting-started/quickstart.mdx b/docs/v5/developer/getting-started/quickstart.mdxnew file mode 100644index 0000000000..22e65ac205--- /dev/null+++ b/docs/v5/developer/getting-started/quickstart.mdx@@ -0,0 +1,89 @@+---+title: "Installing Spree"+sidebarTitle: Installation+description: "Install Spree Commerce locally, run your first store, and deploy it to production with the official starter template."+canonical: "https://spreecommerce.org/docs/developer/getting-started/quickstart"+---++## Using `create-spree-app`++ The quickest way to get started. Scaffolds a full Spree project with Next.js Storefront (optional).++ **Requirements:** [Node.js](https://nodejs.org/) 20+ and [Docker](https://docs.docker.com/get-docker/) running.++ ```bash+ npx create-spree-app@latest my-store+ ```++ The CLI walks you through an interactive setup:++ 1. Choose **Full-stack** (Backend + Next.js Storefront) or **Backend only**+ 2. Optionally load **sample data** (products, categories, images)++ Once complete, your store should be running at [http://localhost:3000/admin](http://localhost:3000/admin). The port can be different if `3000` is already used on your system.++ See the full [create-spree-app documentation](/v5/developer/create-spree-app/quickstart) for all CLI flags and options.++## Accessing Admin Panel++Navigate to [http://localhost:3000/admin](http://localhost:3000/admin) and log in with the default credentials:++| | |+|---|---|+| **Email** | `[email protected]` |+| **Password** | `spree123` |++Upon successful authentication, you should see the admin screen:++<Frame caption="Spree Admin Dashboard">+ <img src="/images/spree_admin_dashboard.png" />+</Frame>++## Using the Spree CLI++Projects scaffolded with `create-spree-app` include [`@spree/cli`](/v5/developer/cli/quickstart) for managing the backend and calling the Admin API. Because it's a project dependency, run it with `npx` (or any package-manager script):++```bash+npx spree dev # boot the Docker stack+npx spree api get products # query the Admin API (read-only key preconfigured)+```++Project setup mints a read-only Admin API key into `.spree/credentials.json` (and `spree api` mints it on first use if you skipped setup), so `spree api` works without any extra configuration.++To call `spree` directly without the `npx` prefix, install the CLI globally:++```bash+npm install -g @spree/cli+spree api get products+```++See the [Spree CLI guide](/v5/developer/cli/quickstart) for all commands and the [Admin API from the CLI](/v5/developer/cli/admin-api) for querying your store's data.++## Next Steps++<CardGroup cols={2}>+ <Card title="Build with AI Agents" icon="bot" href="/developer/agentic/overview">+ Install the Spree agent skills and connect the docs MCP server — Claude Code, Cursor, Copilot, and 60+ other tools learn Spree's conventions and build features with you.+ </Card>+ <Card title="Customization Tutorial" icon="graduation-cap" href="/developer/tutorial/introduction">+ Build a complete custom feature — model, admin UI, API, and TypeScript SDK — step by step.+ </Card>+ <Card title="Core Concepts" icon="brain" href="/developer/core-concepts/architecture">+ Understand how Spree models commerce — stores, products, orders, payments.+ </Card>+ <Card title="Next.js Storefront" icon="react" href="/developer/storefront/nextjs/quickstart">+ Customize and extend the headless storefront.+ </Card>+</CardGroup>++<Tip>+ Using an AI coding agent? Run `npx skills add spree/agent-skills` in your new project — it teaches your agent the customization patterns before you write a line of code. See [Agentic Development](/v5/developer/agentic/overview).+</Tip>++---++Congrats! You've set up your Spree Commerce and it's looking amazing!++Give Spree a [GitHub Star](https://github.com/spree/spree)<Icon icon="star" iconType="solid" color="#FFD43B" />, why don't ya? Thank you for supporting Spree open-source! <Icon icon="heart" iconType="solid" color="#FF0000" />++Need support or want to give some feedback? Join our [Discord](https://discord.spreecommerce.org/)diff --git a/docs/v5/developer/how-to/custom-api-authentication.mdx b/docs/v5/developer/how-to/custom-api-authentication.mdxnew file mode 100644index 0000000000..508bb201d2--- /dev/null+++ b/docs/v5/developer/how-to/custom-api-authentication.mdx@@ -0,0 +1,399 @@+---+title: Integrate a Third-Party Identity Provider+description: Step-by-step guide to plugging a custom identity provider (Auth0, Okta, Firebase, Cognito, or any JWT issuer) into the Spree Store and Admin APIs.+canonical: "https://spreecommerce.org/docs/developer/how-to/custom-api-authentication"+---++import { Since } from '/snippets/since.mdx';++<Since version="5.5" />++## Overview++Both Spree APIs — the customer-facing **Store API** and the back-office **Admin API** — ship with the same pluggable authentication system. You register a **strategy class** for a named provider, and the existing login endpoints dispatch to it — no controller patching, no route overrides, no fork.++By the end of this guide you'll have:++- A custom strategy that verifies a third-party JWT against a JWKS endpoint+- A user account auto-provisioned on first login, reused on subsequent logins+- A standard **Spree-issued JWT + refresh token** returned to the client+- Every API endpoint protected by Spree's own JWT — the third-party token is only used at the login exchange step++### Store vs Admin — what changes++The mechanism is identical for both surfaces. A strategy you write works on either side; only the registry you add it to (and a handful of surface-specific details) differ:++| | Store API (customers) | Admin API (staff) |+|---|---|---|+| Registry | `Spree.store_authentication_strategies` | `Spree.admin_authentication_strategies` |+| User class | `Spree.user_class` | `Spree.admin_user_class` |+| Login endpoint | `POST /api/v3/store/auth/login` | `POST /api/v3/admin/auth/login` |+| Refresh endpoint | `POST /api/v3/store/auth/refresh` | `POST /api/v3/admin/auth/refresh` |+| JWT audience | `aud: store_api` | `aud: admin_api` |+| Refresh token delivery | returned in the response body | set as an `HttpOnly` cookie |+| Strategy base class | `Spree::Authentication::Strategies::BaseStrategy` | *(same)* |++Everything else — the strategy class you write, the `BaseStrategy` helpers, JWT verification, account provisioning, account linking — is the same. The walkthrough below uses the Store API; each step calls out the one-line Admin swap.++## Architecture++The flow below uses the Store API; the Admin API is identical with `admin` in the path and `aud: admin_api` on the issued JWT.++```+Client → POST /api/v3/store/auth/login+ { provider: "my_idp", token: "<third-party JWT>" }+ │+ ▼+ AuthController looks up the strategy by `provider` key+ │+ ▼+ YourStrategy#authenticate+ • verifies the JWT against the IdP's JWKS+ • finds or creates a Spree::UserIdentity → Spree user+ • returns success(user) or failure(message)+ │+ ▼+ Spree issues its own JWT (HS256, iss=spree, aud=store_api)+ + a rotatable RefreshToken+ │+ ▼+Client → subsequent calls with `Authorization: Bearer <Spree JWT>`+```++The third-party JWT proves identity **once, at login**. After that, the client uses the Spree JWT for everything, and `/auth/refresh` rotates it via Spree's own refresh-token mechanism. Your existing CanCanCan rules, `current_user`, and serializer params just work.++## Step 1: Create the Strategy Class++Subclass `Spree::Authentication::Strategies::BaseStrategy` and implement two methods: `provider` (a string identifier) and `authenticate` (returns a `Spree::ServiceModule::Result`).++```ruby app/models/my_app/auth/external_jwt_strategy.rb+module MyApp+ module Auth+ class ExternalJwtStrategy < Spree::Authentication::Strategies::BaseStrategy+ PROVIDER = 'external_idp'.freeze++ def provider+ PROVIDER+ end++ def authenticate+ token = params[:token] || extract_bearer+ return failure(Spree.t('api.unauthorized')) if token.blank?++ payload = verify_with_jwks(token)++ user = find_or_create_user_from_oauth(+ provider: PROVIDER,+ uid: payload.fetch('sub'),+ info: {+ email: payload['email'],+ first_name: payload['given_name'],+ last_name: payload['family_name']+ }+ )++ success(user)+ rescue JWT::DecodeError, JWT::ExpiredSignature, JWT::InvalidIssuerError, JWT::InvalidAudError, KeyError => e+ failure(Spree.t('api.unauthorized'))+ end++ private++ def verify_with_jwks(token)+ jwks_loader = ->(opts) { jwks(force: opts[:kid_not_found]) }++ JWT.decode(+ token, nil, true,+ algorithms: ['RS256'],+ iss: ENV.fetch('EXTERNAL_IDP_ISSUER'),+ aud: ENV.fetch('EXTERNAL_IDP_AUDIENCE'),+ verify_iss: true,+ verify_aud: true,+ jwks: jwks_loader+ ).first+ end++ def jwks(force: false)+ Rails.cache.fetch('external_idp:jwks', expires_in: 1.hour, force: force) do+ uri = URI(ENV.fetch('EXTERNAL_IDP_JWKS_URL'))+ JSON.parse(Net::HTTP.get(uri))+ end+ end++ def extract_bearer+ header = request_env['HTTP_AUTHORIZATION'].to_s+ header.start_with?('Bearer ') ? header.split(' ', 2).last : nil+ end+ end+ end+end+```++### What the base class gives you++`Spree::Authentication::Strategies::BaseStrategy` (in `spree_core`) exposes a few helpers so your subclass stays small:++| Helper | Purpose |+|---|---|+| `success(user)` | Wrap a user in a successful `ServiceModule::Result` |+| `failure(message)` | Wrap an error message in a failed result |+| `find_user_by_email(email)` | Lookup against `Spree.user_class` |+| `find_or_create_user_from_oauth(provider:, uid:, info:, tokens: {})` | Calls `Spree::UserIdentity.find_or_create_from_oauth` with the right `user_class` |+| `params`, `request_env`, `user_class` | Reader access to the controller-supplied inputs |++`find_or_create_user_from_oauth` returns the **user**, not the identity. It creates the `Spree::UserIdentity` row on first login (mapping `provider + uid → user`) and reuses it on subsequent logins — so repeat sign-ins land on the same Spree customer.++## Step 2: Register the Strategy++Add the strategy to a registry in an initializer. **This is the only line that decides which API the provider serves** — `store_authentication_strategies` for customer login, `admin_authentication_strategies` for staff login. Register with both to allow the same provider on either surface. The key you choose here is what clients send as `provider` in the login payload.++<CodeGroup>++```ruby Store API+# config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.store_authentication_strategies.add(:external_idp, MyApp::Auth::ExternalJwtStrategy)+end+```++```ruby Admin API+# config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.admin_authentication_strategies.add(:okta, MyApp::Auth::OktaStrategy)+end+```++```ruby Both+# config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.store_authentication_strategies.add(:external_idp, MyApp::Auth::ExternalJwtStrategy)+ Spree.admin_authentication_strategies.add(:external_idp, MyApp::Auth::ExternalJwtStrategy)+end+```++</CodeGroup>++Both registries are a `Spree::Authentication::StrategyRegistry` with the same API:++| Method | Purpose |+|---|---|+| `add(key, strategy_class)` | Register a strategy. Overwrites any existing entry under the same key — that's how you swap the built-in `:email` strategy. |+| `remove(key)` | Unregister a strategy. Idempotent (returns `nil` if the key was never registered). |+| `[key]` | Look up a registered class. |+| `key?(key)`, `keys`, `values`, `each`, `to_h` | Standard introspection. |++The strategy is instantiated with the surface's user class automatically — `Spree.user_class` from the store registry, `Spree.admin_user_class` from the admin registry — and your `authenticate` reads it via the `user_class` helper, so the same class provisions customers on one side and staff on the other.++<Tip>+Restrict a surface to SSO by removing the built-in email/password strategy after adding yours: `Spree.admin_authentication_strategies.remove(:email)` locks staff to your provider; the store side stays on email/password.+</Tip>++<Warning>+`Spree::UserIdentity` validates that `provider` is a registered strategy key. Registration must happen during boot — before the first login attempt.+</Warning>++## Step 3: Call the Exchange Endpoint++The login endpoint is the single dispatcher — `/api/v3/store/auth/login` for customers, `/api/v3/admin/auth/login` for staff. The `provider` field in the body selects the strategy — omit it for built-in email/password, set it to your registered key for everything else. The remaining body fields are whatever your strategy reads from `params`.++<CodeGroup>++```http Store API+POST /api/v3/store/auth/login+X-Spree-API-Key: pk_your_publishable_key+Content-Type: application/json++{+ "provider": "external_idp",+ "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIs..."+}+```++```http Admin API+POST /api/v3/admin/auth/login+X-Spree-API-Key: sk_your_secret_key+Content-Type: application/json++{+ "provider": "okta",+ "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIs..."+}+```++</CodeGroup>++The response is the standard Spree auth payload. The difference is the refresh token: the **Store API returns it in the body**, while the **Admin API sets it as an `HttpOnly` cookie** scoped to `/api/v3/admin/auth` and omits it from the body.++<CodeGroup>++```json Store API+{+ "token": "<Spree HS256 JWT, aud=store_api>",+ "refresh_token": "rt_xxxxxxxxxxxx",+ "user": { "id": "user_...", "email": "...", "...": "..." }+}+```++```json Admin API+{+ "token": "<Spree HS256 JWT, aud=admin_api>",+ "user": { "id": "user_...", "email": "...", "...": "..." }+}+```++The refresh token arrives as a `Set-Cookie: spree_admin_refresh_token=…; HttpOnly; Path=/api/v3/admin/auth` response header rather than in the body.++</CodeGroup>++From here, the client sends `Authorization: Bearer <Spree JWT>` on every subsequent call. When the JWT expires (default: 1 hour), it rotates via the refresh endpoint — the Store API takes the refresh token in the body of `POST /api/v3/store/auth/refresh`; the Admin API drives `POST /api/v3/admin/auth/refresh` entirely from the cookie (see [Admin Auth & Cookie Refresh](/api-reference/admin-api/authentication)).++The SDKs wrap the same exchange — `@spree/sdk` for the Store API, `@spree/admin-sdk` for the Admin API:++<CodeGroup>++```ts Store SDK+import { createClient } from '@spree/sdk'++const client = createClient({ baseUrl: 'https://your-store.com', publishableKey: '<pk>' })++const auth = await client.auth.login({+ provider: 'external_idp',+ token: thirdPartyJwt,+})+```++```ts Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({ baseUrl: 'https://your-store.com' })++// Refresh token lands in the HttpOnly cookie; only the access token comes back here.+const auth = await client.auth.login({+ provider: 'okta',+ token: thirdPartyJwt,+})+```++</CodeGroup>++`LoginCredentials` is a discriminated union — pass `{ email, password }` for the built-in strategy, or `{ provider, ...customFields }` for any strategy you registered.++## Account Linking++The naive flow above will create a brand new Spree user the first time a given `(provider, uid)` is seen — even if a user with the same email already exists from a password signup. If you want **same-email-means-same-customer**, look up by email first and attach an identity to the existing user:++```ruby+def authenticate+ payload = verify_with_jwks(params[:token])+ email = payload.fetch('email')++ user = find_user_by_email(email)++ if user+ user.identities.find_or_create_by!(provider: PROVIDER, uid: payload['sub']) do |identity|+ identity.info = { email: email, name: payload['name'] }+ end+ else+ user = find_or_create_user_from_oauth(+ provider: PROVIDER,+ uid: payload['sub'],+ info: { email: email, first_name: payload['given_name'], last_name: payload['family_name'] }+ )+ end++ success(user)+end+```++<Warning>+**Only link by email if your IdP guarantees `email_verified`.** Silent linking against an unverified email is a known account-takeover vector: an attacker registers `[email protected]` at the IdP without proving ownership, then logs into Spree as the real victim. Check the `email_verified` claim (or equivalent) before linking, and reject otherwise.+</Warning>++## Logout++<CodeGroup>++```http Store API+POST /api/v3/store/auth/logout+Content-Type: application/json++{ "refresh_token": "rt_xxxxxxxxxxxx" }+```++```http Admin API+POST /api/v3/admin/auth/logout+Content-Type: application/json++# No body — the refresh token is read from the HttpOnly cookie and cleared.+```++</CodeGroup>++This revokes the Spree refresh token. The Spree JWT itself remains valid until it expires naturally (short-lived by design — default 1 hour). Spree does **not** call the IdP's revocation endpoint; if you need single sign-out, do that from the client.++## Security Notes++A few things worth getting right:++- **Don't try to pass the third-party JWT through to protected endpoints.** Spree's `JwtAuthentication` concern verifies `iss: 'spree'` and the expected audience (`store_api` or `admin_api`) with HS256 against the Spree secret — a foreign RS256 token will never validate, and you don't want it to. The exchange-at-login model is the right one.+- **JWKS caching and rotation.** Cache the JWKS (the example uses a 1-hour TTL) but make sure your loader honors the `kid_not_found: true` option so that an unrecognized `kid` triggers a refetch. Otherwise key rotation at the IdP locks users out for up to the TTL.+- **Validate `iss` and `aud` claims.** Always. The example passes `verify_iss: true, verify_aud: true` to `JWT.decode` — don't drop those.+- **Algorithm pinning.** Hard-code `algorithms: ['RS256']` (or whatever your IdP uses). Never let the token's own `alg` header decide — the classic `alg: none` and HS-as-RS confusion attacks both exploit lax algorithm selection.+- **Rate limiting.** `POST /auth/login` is rate-limited per IP via `Spree::Api::Config[:rate_limit_login]`. Tune it in your app config if needed — the same limit applies to email/password and provider-dispatched logins.++## Testing++A strategy is a plain Ruby class — test it in isolation without booting a controller:++```ruby spec/models/my_app/auth/external_jwt_strategy_spec.rb+require 'rails_helper'++RSpec.describe MyApp::Auth::ExternalJwtStrategy do+ let(:rsa_private) { OpenSSL::PKey::RSA.generate(2048) }+ let(:jwks) { { keys: [JWT::JWK.new(rsa_private).export] } }++ let(:token) do+ JWT.encode(+ { sub: 'idp-user-123', email: '[email protected]', iss: 'https://idp.example', aud: 'spree' },+ rsa_private, 'RS256'+ )+ end++ before do+ stub_request(:get, ENV['EXTERNAL_IDP_JWKS_URL']).to_return(body: jwks.to_json)+ end++ subject(:result) do+ described_class.new(+ params: { provider: 'external_idp', token: token },+ request_env: {}+ ).authenticate+ end++ it 'provisions a Spree user on first login' do+ expect { result }.to change(Spree.user_class, :count).by(1)+ expect(result).to be_success+ expect(result.value.email).to eq('[email protected]')+ end++ it 'reuses the user on subsequent logins' do+ described_class.new(params: { token: token }, request_env: {}).authenticate+ expect { result }.not_to change(Spree.user_class, :count)+ end++ it 'fails on an expired token' do+ expired = JWT.encode({ sub: 'x', exp: 1.hour.ago.to_i, iss: 'https://idp.example', aud: 'spree' }, rsa_private, 'RS256')+ result = described_class.new(params: { token: expired }, request_env: {}).authenticate+ expect(result).not_to be_success+ end+end+```++## Reference++- `Spree::Authentication::Strategies::BaseStrategy` — `spree/core/app/models/spree/authentication/strategies/base_strategy.rb`+- `Spree::UserIdentity` — `spree/core/app/models/spree/user_identity.rb`+- `Spree::Api::V3::Store::AuthController` — `spree/api/app/controllers/spree/api/v3/store/auth_controller.rb`+- `Spree::Api::V3::Admin::AuthController` — `spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb`+- `Spree::Api::V3::JwtAuthentication` — `spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb`+- See also: [Staff & Roles](/v5/developer/core-concepts/staff-roles) for the admin login flow, [Customers](/v5/developer/core-concepts/customers) for storefront auth, and [Authentication](/v5/developer/customization/authentication) for `Spree.user_class` integration.diff --git a/docs/v5/developer/how-to/custom-order-routing.mdx b/docs/v5/developer/how-to/custom-order-routing.mdxnew file mode 100644index 0000000000..ba18103f0b--- /dev/null+++ b/docs/v5/developer/how-to/custom-order-routing.mdx@@ -0,0 +1,322 @@+---+title: Build Custom Order Routing+description: Step-by-step guide to extending Spree's order routing — write custom rules to add new signals, or a custom strategy to replace the algorithm entirely.+canonical: "https://spreecommerce.org/docs/developer/how-to/custom-order-routing"+---++import { Since } from '/snippets/since.mdx';++<Since version="5.5" />++## Overview++Order routing decides which [Stock Location](/v5/developer/core-concepts/inventory#stock-locations) fulfills an order at checkout. Spree gives you two extension points:++- **Rules** — add a new signal to the existing rules-walking algorithm (proximity, customer tier, refrigerated SKUs, day-of-week dispatch).+- **Strategies** — replace the algorithm entirely (delegate to a warehouse management system, run an ML model, call an optimization solver).++This guide covers both. Most extensions are rules — they compose with the built-ins and don't require rewriting the pipeline.++Before starting, make sure you understand [how order routing works in Spree](/v5/developer/core-concepts/shipments#order-routing).++| If the answer is "yes" | Pick |+|---|---|+| Could this work just by reordering or adding signals to the existing algorithm? | A **rule** |+| Does the data live in another system you have to call? | A **strategy** |+| Will the algorithm need access to multiple orders simultaneously (batching, capacity-aware)? | A **strategy** |+| Are you replacing the entire decision (no rules at all)? | A **strategy** |++## Custom Routing Rules++A rule is one input to the rules-walking algorithm. Each rule subclasses `Spree::OrderRoutingRule` and implements `#rank`, returning an array of `LocationRanking` — one per candidate location.++### Step 1: Create the Rule Class++```ruby app/models/spree/order_routing/rules/closest_location.rb+module Spree+ module OrderRouting+ module Rules+ class ClosestLocation < Spree::OrderRoutingRule+ preference :max_distance_km, :integer, default: 1000++ def rank(order, locations)+ target = order.ship_address&.coordinates+ return locations.map { |l| LocationRanking.new(location: l, rank: nil) } if target.nil?++ locations.map do |loc|+ distance = loc.distance_from(target)+ ranked = distance && distance <= preferred_max_distance_km ? distance.to_i : nil+ LocationRanking.new(location: loc, rank: ranked)+ end+ end+ end+ end+ end+end+```++#### Key Method to Implement++| Method | Required | Description |+|--------|----------|-------------|+| `rank(order, locations)` | Yes | Returns one `LocationRanking` per input location. Lower rank wins (`0` is best); `nil` means abstain (the rule has no opinion about that location and is skipped for that pass). |++#### Using Preferences++Rules use Spree's preference system for configuration, the same way [Promotion Rules](/v5/developer/how-to/custom-promotion#using-preferences) do. Each preference creates getter/setter methods automatically:++```ruby+preference :max_distance_km, :integer, default: 1000++# Creates:+# preferred_max_distance_km / preferred_max_distance_km=+```++Available types: `:string`, `:integer`, `:decimal`, `:boolean`, `:array`.++### Step 2: Activate the Rule on a Channel++Every routing rule belongs to a Channel. Pick the channel(s) you want it active on and insert a row:++```ruby+store = Spree::Store.default+channel = store.default_channel++Spree::OrderRouting::Rules::ClosestLocation.create!(+ store: store,+ channel: channel,+ position: 0, # before the seeded preferred_location rule+ preferred_max_distance_km: 500+)+```++Register the rule kind so it's available to add and passes the `type` validation. Spree's autoloader picks up the model under `app/models/`; the registry is the curated allowlist (it also drives admin pickers):++```ruby+# config/initializers/spree.rb+Spree.order_routing.rules << 'AcmeFresh::OrderRouting::RefrigeratedRule'.constantize+```++To activate the rule across multiple channels, create one row per channel. That keeps each channel's rule list explicit and lets you tune per-channel preferences independently.++### Rank Semantics++The reducer composes rules using "first non-tie wins":++| Situation | What the reducer does |+|---|---|+| All rules abstain (`nil`) for a location | Falls back to `StockLocation.default`, then by `id` |+| One rule returns a unique minimum rank | That location wins; remaining rules skipped |+| One rule returns a tied minimum | The tied locations carry forward; the next rule weighs in *only on those* |+| All rules tie through the whole chain | Final tiebreak: default location, then by `id` |++Practical implications:++- **Returning `0` for everything is a reset.** If every location ties at `0`, all locations carry forward — the reducer treats it as "no signal" and moves on.+- **Coverage-style metrics negate.** When higher-is-better, return `-coverage` so lower wins. See `Spree::OrderRouting::Rules::MinimizeSplits` for the canonical example.+- **Abstaining yields to other rules.** `nil` is the right answer when your rule has no opinion — it lets later rules decide.++### Step 3: Test the Rule++```ruby spec/models/spree/order_routing/rules/closest_location_spec.rb+require 'rails_helper'++RSpec.describe Spree::OrderRouting::Rules::ClosestLocation, type: :model do+ let(:store) { @default_store }+ let(:channel) { store.default_channel }+ let(:near) { create(:stock_location, latitude: 40.71, longitude: -74.00) } # NYC+ let(:far) { create(:stock_location, latitude: 34.05, longitude: -118.24) } # LA+ let(:order) { build(:order, store: store, ship_address: build(:address, latitude: 40.75, longitude: -73.99)) }++ subject(:rule) do+ described_class.new(store: store, channel: channel, position: 99, preferred_max_distance_km: 5000)+ end++ it 'ranks the closer location lower' do+ rankings = rule.rank(order, [near, far])+ expect(rankings.find { |r| r.location == near }.rank).to be < rankings.find { |r| r.location == far }.rank+ end++ it 'abstains for every location when the order has no shippable address' do+ addressless_order = build(:order, store: store, ship_address: nil)+ rankings = rule.rank(addressless_order, [near, far])+ expect(rankings.map(&:rank)).to all(be_nil)+ end+end+```++### Common Pitfalls++- **Forgetting `position`.** `position` is required and `acts_as_list`-scoped per channel. Use a number that doesn't collide with the seeded `1` / `2` / `3` (low for "before the defaults", `100+` for "after the defaults").+- **Returning fewer rankings than locations.** Always return one entry per input location, including abstains (`nil` rank). The reducer needs to see every location.+- **Trying to "block" a location.** Rules rank, they don't filter. To exclude a location, lower its rank to a value worse than every other rule produces, or abstain everywhere except the locations you want and rely on a later rule to cover the rest.++## Custom Routing Strategies++A strategy is a complete algorithm — when rules-walking doesn't fit your problem, you write a strategy that owns the entire allocation pipeline.++### Step 1: Create the Strategy Class++The contract is `Spree::OrderRouting::Strategy::Base`. There are no defaults — you implement all four methods:++| Method | When it fires | Returns |+|---|---|---|+| `#for_allocation` | Cart → checkout transition (`Order#create_proposed_shipments`) | `Array<Spree::Stock::Package>` |+| `#for_sale(fulfillment:)` | A shipment ships | (side effect) |+| `#for_release` | An in-flight order is canceled before shipping | (side effect) |+| `#for_cancellation` | A shipped order is canceled (return) | (side effect) |++The four methods bracket the lifecycle: allocation → sale, allocation → release, or allocation → cancellation. Whatever your algorithm does at allocation time, the other three are where you reverse or settle it.++```ruby app/models/acme/oms/strategy.rb+module Acme+ module Oms+ class Strategy < Spree::OrderRouting::Strategy::Base+ def for_allocation+ decision = client.allocate(order_payload)+ return [] if decision.assignments.empty?++ decision.assignments.map { |assignment| build_package(assignment) }+ end++ def for_sale(fulfillment:)+ client.notify_shipped(fulfillment_payload(fulfillment))+ end++ def for_release+ client.release(order.number)+ end++ def for_cancellation+ client.cancel_and_restock(order.number)+ end++ private++ def client+ @client ||= Acme::Oms::Client.new(api_key: ENV.fetch('ACME_OMS_API_KEY'))+ end++ def order_payload+ {+ order_number: order.number,+ line_items: order.line_items.map { |li| { sku: li.variant.sku, qty: li.quantity } },+ ship_to: order.ship_address&.country&.iso+ }+ end++ def build_package(assignment)+ location = Spree::StockLocation.find_by!(code: assignment.location_code)+ units = order.inventory_units.where(variant_id: assignment.variant_ids).to_a++ package = Spree::Stock::Packer.new(location, units, Spree.stock_splitters).packages.first+ package.shipping_rates = Spree::Stock::Estimator.new(order).shipping_rates(package)+ package+ end++ def fulfillment_payload(fulfillment)+ # ...+ end+ end+ end+end+```++Notes:++- **Strategies are plain Ruby classes**, not ActiveRecord models. Live under `app/models/` so the autoloader picks them up; or anywhere on the load path if you'd rather organize them as services.+- **`for_allocation` returns `Spree::Stock::Package` objects.** The order's `create_proposed_shipments` turns those into `Shipment`s by calling `package.to_shipment`. Returning shipments directly will break the call site.+- **Reuse the existing primitives.** `Spree::Stock::Packer`, `Spree::Stock::Estimator`, and `Spree::Stock::InventoryUnitBuilder` handle packing, rate estimation, and inventory unit construction. Custom strategies are about the location decision, not re-implementing the packing pipeline.++### Step 2: Register the Strategy++First register the class so it's selectable (this is the allowlist the model validation checks against, and the source for admin strategy pickers):++```ruby+# config/initializers/spree.rb+Spree.order_routing.strategies << 'Acme::Oms::Strategy'.constantize+```++Then select it by class name string — set on `Spree::Store` (default) or `Spree::Channel` (override). Setting an unregistered class fails validation.++Activate on the whole store:++```ruby+Spree::Store.default.update!(+ preferred_order_routing_strategy: 'Acme::Oms::Strategy'+)+```++Override on one channel only:++```ruby+store = Spree::Store.default+store.channels.find_by(code: 'pos').update!(+ preferred_order_routing_strategy: 'Acme::Oms::Strategy'+)+```++Resolution order: `channel.preferred_order_routing_strategy` → `store.preferred_order_routing_strategy` → the default `Strategy::Rules`. Only a value pointing to a **registered** `Strategy::Base` subclass is used; anything unset, unregistered, or invalid is skipped, so a misconfiguration (or a strategy you've since unregistered) falls back to the default instead of breaking checkout.++### Step 3: Test the Strategy++Strategy tests are integration tests — build an order, instantiate the strategy, exercise the four methods, assert on the resulting shipments and mocked side effects.++```ruby spec/models/acme/oms/strategy_spec.rb+require 'rails_helper'++RSpec.describe Acme::Oms::Strategy, type: :model do+ let(:store) { @default_store }+ let(:variant) { create(:variant) }+ let(:location) { create(:stock_location, code: 'NYC') }+ let(:order) { create(:order_with_line_items, store: store, line_items_attributes: [{ variant: variant, quantity: 1 }]) }++ before { location.stock_item_or_create(variant).update!(count_on_hand: 10) }++ subject(:strategy) { described_class.new(order: order) }++ describe '#for_allocation' do+ it 'returns packages from the OMS-chosen locations' do+ stub_oms_decision(assignments: [{ location_code: 'NYC', variant_ids: [variant.id] }])++ packages = strategy.for_allocation+ expect(packages.map(&:stock_location)).to all(eq(location))+ end++ it 'returns no packages when the OMS has nothing to assign' do+ stub_oms_decision(assignments: [])+ expect(strategy.for_allocation).to eq([])+ end+ end+end+```++### Common Pitfalls++- **Forgetting the lifecycle hooks.** `for_release` and `for_cancellation` raise `NotImplementedError` by default. If your algorithm doesn't need post-allocation hooks, override them as no-ops explicitly.+- **Ignoring inventory.** Even custom strategies should query `Spree::StockLocation.active` and respect the order's reserved units. Hardcoding `Spree::StockLocation.first` will work in tests and break in production.+- **Side effects in `for_sale` / `for_release`.** These fire from state-machine callbacks where the order may already be partially mutated. Treat the methods as side-effect endpoints; pull what you need from the `order` and `fulfillment` arguments — don't reload state mid-call.++## Coexistence with Stock Reservations++Stock reservations and order routing are independent systems in 5.5 — they make decisions at different times and protect different invariants.++| Concern | Reservation system | Order routing |+|---|---|---|+| **When it fires** | Cart mutation (add item, change qty, enter checkout) | Cart → checkout transition |+| **What it decides** | How many units of a variant are held for this cart | Which `StockLocation` fulfills the order |+| **Granularity** | Per-variant | Per-order |++`Spree::Stock::Quantifier` already subtracts active reservations from `count_on_hand` per-variant across all locations, so global "can we sell this variant?" math is correct even when the reservation and the routing decision land on different locations.++What this means for you when writing custom rules and strategies:++- **Don't read `StockReservation` from inside a routing rule's `#rank`.** The reservations were created against arbitrary stock_items at cart time and don't reflect the routing decision.+- **Don't relocate reservations from a custom strategy's `for_allocation`.** That's the path 6.0 codifies; doing it ad-hoc in 5.5 races against the cart services that own reservation lifecycle.+- **`AvailabilityValidator` is the safety net.** If a routing decision picks a location that's actually short on stock, the validator catches it before the order completes.++## Next Steps++- [How orders work](/v5/developer/core-concepts/orders) — Order lifecycle and the routing context+- [Inventory & Stock Locations](/v5/developer/core-concepts/inventory) — Where the locations live+- [Build Custom Promotion Rules & Actions](/v5/developer/how-to/custom-promotion) — A similar STI-based extension patterndiff --git a/docs/v5/developer/how-to/custom-payment-method.mdx b/docs/v5/developer/how-to/custom-payment-method.mdxnew file mode 100644index 0000000000..b075789085--- /dev/null+++ b/docs/v5/developer/how-to/custom-payment-method.mdx@@ -0,0 +1,377 @@+---+title: Build a Custom Payment Method+description: Step-by-step guide to creating a custom payment gateway integration with Payment Sessions, 3D Secure, and PCI compliance.+canonical: "https://spreecommerce.org/docs/developer/how-to/custom-payment-method"+---++## Overview++This guide walks you through building a custom payment method integration for Spree. By the end, you'll have a fully functional payment gateway that:++- Appears as a payment option during checkout+- Uses Payment Sessions for PCI-compliant payment collection+- Supports 3D Secure and alternative payment methods+- Handles webhooks for reliable payment confirmation+- Optionally supports saving payment methods for future use (Payment Setup Sessions)++Before starting, make sure you understand [how payments work in Spree](/v5/developer/core-concepts/payments).++## Step 1: Create the Payment Method Model++Create a new model inheriting from `Spree::PaymentMethod`. This is the central class that defines how your gateway processes payments.++```ruby app/models/my_gateway.rb+class MyGateway < Spree::PaymentMethod+ preference :api_key, :string+ preference :publishable_key, :string+ preference :webhook_secret, :string++ def payment_icon_name+ 'my-gateway'+ end+end+```++## Step 2: Register the Payment Method++Add your gateway to the list of available payment methods so it appears in the admin panel:++```ruby config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.payment_methods << MyGateway+end+```++After restarting your server, you can select "MyGateway" when creating a new payment method in the admin panel under **Settings > Payments**.++## Step 3: Add Payment Session Support++Payment Sessions are the modern, PCI-compliant way to handle payments. Your gateway creates a session with the provider, the frontend collects payment details using the provider's SDK, and Spree records the result.++### Define the STI Subclass++Create a Payment Session subclass for your gateway. This uses Single Table Inheritance (STI) on the `spree_payment_sessions` table:++```ruby app/models/spree/payment_sessions/my_gateway.rb+module Spree+ module PaymentSessions+ class MyGateway < Spree::PaymentSession+ # Add gateway-specific helper methods here++ def client_secret+ external_data['client_secret']+ end+ end+ end+end+```++### Implement Session Methods on the Gateway++Override the key methods on your `PaymentMethod` subclass:++```ruby app/models/my_gateway.rb+class MyGateway < Spree::PaymentMethod+ preference :api_key, :string+ preference :publishable_key, :string+ preference :webhook_secret, :string++ # Tell Spree this gateway uses Payment Sessions+ def session_required?+ true+ end++ # Return the STI subclass+ def payment_session_class+ Spree::PaymentSessions::MyGateway+ end++ # No source required upfront — it's created when the session completes+ def source_required?+ false+ end++ # Create a session with your payment provider+ def create_payment_session(order:, amount: nil, external_data: {})+ total = amount || order.total_minus_store_credits++ # Call your provider's API to create a payment session+ provider_session = MyProvider::Client.new(preferred_api_key).create_session(+ amount: (total * 100).to_i, # amount in cents+ currency: order.currency,+ metadata: { order_number: order.number }+ )++ payment_sessions.create!(+ order: order,+ amount: total,+ currency: order.currency,+ external_id: provider_session.id,+ external_data: {+ client_secret: provider_session.client_secret+ },+ customer: order.user+ )+ end++ # Update an existing session (e.g., when order total changes)+ def update_payment_session(payment_session:, amount: nil, external_data: {})+ if amount.present?+ MyProvider::Client.new(preferred_api_key).update_session(+ payment_session.external_id,+ amount: (amount * 100).to_i+ )+ payment_session.update!(amount: amount)+ end++ payment_session+ end++ # Complete the session after the customer pays on the frontend.+ #+ # Responsibilities:+ # - Verify payment status with the provider+ # - Create the Spree::Payment record+ # - Transition the payment to the correct state+ # - Mark the session as completed/failed+ #+ # Must NOT complete the order — that is handled by Carts::Complete+ # (called by the frontend or by the webhook handler).+ def complete_payment_session(payment_session:, params: {})+ # Verify the payment with your provider+ result = MyProvider::Client.new(preferred_api_key).retrieve_session(+ payment_session.external_id+ )++ if result.status == 'succeeded'+ payment_session.process!++ # Create the Spree::Payment record+ payment = payment_session.find_or_create_payment!++ # Transition the payment to completed+ if payment.present? && !payment.completed?+ payment.started_processing! if payment.checkout?+ payment.complete! if payment.can_complete?+ end++ payment_session.complete!+ else+ payment_session.fail!+ end+ end++ def payment_icon_name+ 'my-gateway'+ end+end+```++### How the Frontend Uses It++The frontend creates a session, then uses the provider's SDK to collect payment:++```typescript+// 1. Get available payment methods+const methods = await client.carts.paymentMethods.list(cart.id, options)++// 2. Find your gateway (check session_required flag)+const myGateway = methods.find(m => m.session_required)++// 3. Create a payment session (after shipping is selected so amount is correct)+const session = await client.carts.paymentSessions.create(cart.id, {+ payment_method_id: myGateway.id,+}, options)++// 4. Use the client_secret with your provider's frontend SDK+const result = await MyProviderSDK.confirmPayment(session.external_data.client_secret)++// 5. Complete the payment session (creates Payment record, does NOT complete order)+const completed = await client.carts.paymentSessions.complete(+ cart.id, session.id,+ { session_result: result.id },+ options+)++// 6. Complete the order+const order = await client.carts.complete(cart.id, options)+```++<Info>+**Important:** Always create the payment session **after** shipping is selected. If the order total changes (shipping rate change, coupon applied), create a new payment session with the updated amount. The `complete` call in step 5 only handles payment — step 6 finalizes the order.+</Info>++## Step 4: Handle Webhooks (Recommended)++Webhooks ensure payments are captured even if the customer closes their browser after paying. Spree provides a generic webhook endpoint at `POST /api/v3/webhooks/payments/:payment_method_id` — you don't need to create your own controller or routes.++Your gateway just needs to implement `parse_webhook_event` to normalize the provider-specific payload:++```ruby app/models/my_gateway.rb+class MyGateway < Spree::PaymentMethod+ # ... existing code ...++ # Parse incoming webhook from your payment provider.+ #+ # @param raw_body [String] the raw request body+ # @param headers [Hash] the request headers+ # @return [Hash, nil] normalized result, or nil for unsupported events+ # @raise [Spree::PaymentMethod::WebhookSignatureError] if signature is invalid+ def parse_webhook_event(raw_body, headers)+ # 1. Verify the webhook signature+ signature = headers['HTTP_X_SIGNATURE']+ unless MyProvider::Webhook.verify(raw_body, signature, preferred_webhook_secret)+ raise Spree::PaymentMethod::WebhookSignatureError+ end++ # 2. Parse the payload+ event = JSON.parse(raw_body)++ # 3. Return a normalized result+ case event['type']+ when 'payment.succeeded'+ session = Spree::PaymentSession.find_by(external_id: event.dig('data', 'session_id'))+ return nil unless session++ { action: :captured, payment_session: session }+ when 'payment.failed'+ session = Spree::PaymentSession.find_by(external_id: event.dig('data', 'session_id'))+ return nil unless session++ { action: :failed, payment_session: session }+ else+ nil # Unsupported event — Spree will return 200 OK and ignore it+ end+ end+end+```++**That's it.** Spree handles the rest:+- Verifies the signature synchronously (returns `401` if `WebhookSignatureError` is raised)+- Enqueues a background job (`Spree::Payments::HandleWebhookJob`) for async processing+- Returns `200 OK` immediately to prevent provider retries+- The job creates/updates the `Payment` record, marks the session completed, and completes the order++The webhook URL for your payment method is available via `payment_method.webhook_url` — register this with your provider during setup.++### Supported Webhook Actions++| Action | Description |+|--------|-------------|+| `:captured` | Payment was captured (charged). Creates payment and completes order. |+| `:authorized` | Payment was authorized (not yet captured). Creates payment and completes order. |+| `:failed` | Payment failed. Marks the session as failed. |+| `:canceled` | Payment was canceled. Marks the session as canceled. |++## Step 5: Control Payment Method Visibility (Optional)++Override visibility methods to control where and when your payment method appears:++```ruby app/models/my_gateway.rb+class MyGateway < Spree::PaymentMethod+ # Only show for stores that support specific currencies+ def available_for_store?(store)+ store.supported_currencies.include?('EUR')+ end++ # Only show for orders above a certain amount+ def available_for_order?(order)+ order.total > 10 && order.currency == 'EUR'+ end+end+```++## Step 6: Add Payment Setup Session Support (Optional)++If your provider supports saving payment methods for future use (like Stripe's SetupIntent), you can add Payment Setup Session support:++```ruby app/models/my_gateway.rb+class MyGateway < Spree::PaymentMethod+ # ... existing code ...++ def setup_session_supported?+ true+ end++ def payment_setup_session_class+ Spree::PaymentSetupSessions::MyGateway+ end++ def create_payment_setup_session(customer:, external_data: {})+ provider_setup = MyProvider::Client.new(preferred_api_key).create_setup_session(+ customer_id: find_or_create_provider_customer(customer)+ )++ payment_setup_sessions.create!(+ customer: customer,+ external_id: provider_setup.id,+ external_client_secret: provider_setup.client_secret+ )+ end++ def complete_payment_setup_session(setup_session:, params: {})+ result = MyProvider::Client.new(preferred_api_key).retrieve_setup_session(+ setup_session.external_id+ )++ if result.status == 'succeeded'+ # Create a saved payment source+ credit_card = Spree::CreditCard.create!(+ payment_method: self,+ user: setup_session.customer,+ gateway_payment_profile_id: result.payment_method_id,+ cc_type: result.card_brand,+ last_digits: result.card_last4,+ month: result.card_exp_month,+ year: result.card_exp_year,+ name: result.cardholder_name+ )++ setup_session.update!(+ payment_source: credit_card+ )+ setup_session.complete!+ else+ setup_session.fail!+ end++ setup_session+ end+end+```++And the STI subclass:++```ruby app/models/spree/payment_setup_sessions/my_gateway.rb+module Spree+ module PaymentSetupSessions+ class MyGateway < Spree::PaymentSetupSession+ end+ end+end+```++## Gateway Options Reference++For every gateway action (authorize, purchase, capture, void, credit), Spree passes a hash of gateway options:++| Option | Description |+|--------------------|-----------------------------------------------------------------------------------------------|+| `email` and `customer` | The email address related to the order |+| `ip` | The last IP address for the order |+| `order_id` | The Order's `number` attribute, plus the `identifier` for each payment |+| `shipping` | The total shipping cost for the order, in cents |+| `tax` | The total tax cost for the order, in cents |+| `subtotal` | The item total for the order, in cents |+| `currency` | The 3-character currency code for the order |+| `discount` | The promotional discount applied to the order |+| `billing_address` | A hash containing billing address information |+| `shipping_address` | A hash containing shipping address information |++## Related Documentation++- [Payments](/v5/developer/core-concepts/payments) - Payment architecture and core concepts+- [Checkout Customization](/v5/developer/customization/checkout) - Customizing the checkout flow+- [Events](/v5/developer/core-concepts/events) - Subscribe to payment events+- [Stripe Integration](/integrations/payments/stripe) - Reference implementation using Stripe+- [Adyen Integration](/integrations/payments/adyen) - Reference implementation using Adyendiff --git a/docs/v6/developer/how-to/custom-promotion.mdx b/docs/v5/developer/how-to/custom-promotion.mdxsimilarity index 50%rename from docs/v6/developer/how-to/custom-promotion.mdxrename to docs/v5/developer/how-to/custom-promotion.mdxindex f4031bc5a0..21799db435 100644--- a/docs/v6/developer/how-to/custom-promotion.mdx+++ b/docs/v5/developer/how-to/custom-promotion.mdx@@ -1,17 +1,19 @@---title: Build Custom Promotion Rules & Actions-description: Step-by-step guide to creating custom promotion rules, discount actions, and adjusters for business-specific eligibility logic and charges.+description: Step-by-step guide to creating custom promotion rules and actions for business-specific eligibility logic and discount behaviors.+canonical: "https://spreecommerce.org/docs/developer/how-to/custom-promotion"---## Overview-Spree's promotion system has three extension points:+Spree's promotion system is built around two extension points: **Rules** (eligibility conditions) and **Actions** (what happens when a promotion applies). While Spree ships with a comprehensive set of [built-in rules and actions](/v5/developer/core-concepts/promotions#rules), you can create custom ones for business-specific logic.-- **Rules** — conditions that decide when a promotion applies-- **Actions** — what an applied promotion does, usually writing [Discount](/v6/developer/core-concepts/taxes-discounts-fees#discounts) rows-- **Adjusters** — for discounts and fees that aren't promotions at all (loyalty pricing, gift wrap fees, payment surcharges)+This guide covers:+- Creating a custom promotion rule with admin UI+- Creating a custom promotion action with a calculator+- Understanding the `eligible?`, `actionable?`, and `perform` contracts-Spree ships with a comprehensive set of [built-in rules and actions](/v6/developer/core-concepts/promotions#rules). This guide shows how to build your own of each kind.+Before starting, make sure you understand [how promotions work in Spree](/v5/developer/core-concepts/promotions).## Custom Promotion Rules@@ -29,7 +31,7 @@ module Spreepreference :quantity, :integer, default: 5def applicable?(promotable)- promotable.is_a?(Spree::Order) || promotable.is_a?(Spree::Cart)+ promotable.is_a?(Spree::Order)enddef eligible?(order, options = {})@@ -55,16 +57,12 @@ end| Method | Required | Description ||--------|----------|-------------|-| `applicable?(promotable)` | Yes | Returns `true` if this rule type can evaluate the promotable — accept both carts and orders (see the note below) |+| `applicable?(promotable)` | Yes | Returns `true` if this rule type can evaluate the promotable (usually `promotable.is_a?(Spree::Order)`) || `eligible?(promotable, options = {})` | Yes | Returns `true` if the promotable meets this rule's conditions. Add messages to `eligibility_errors` to explain why not. |-| `actionable?(line_item)` | No | Returns `true` if a specific line item should receive the promotion's discount. Defaults to `true`. Override this for rules that target specific items (like product or category rules). |+| `actionable?(line_item)` | No | Returns `true` if a specific line item should receive the promotion's action. Defaults to `true`. Override this for rules that target specific items (like product or category rules). |The `options` hash passed to `eligible?` can include `:user`, `:email`, and other context from the checkout flow.-<Warning>-Accept **both** `Spree::Cart` and `Spree::Order` in `applicable?`. Promotions are evaluated on every cart change, long before the cart becomes an order, and in Spree 6 a cart is its own model rather than an unfinished order. A rule guarding on `Spree::Order` alone silently never applies during checkout — the promotion just appears not to work. Every built-in rule accepts both.-</Warning>-#### Using PreferencesRules use Spree's preference system for configuration. Each preference creates getter/setter methods automatically:@@ -84,30 +82,43 @@ Available types: `:string`, `:integer`, `:decimal`, `:boolean`, `:array`.### Step 2: Register the Rule+Add your rule to the promotion configuration so it appears in the admin panel:+```ruby config/initializers/spree.rbRails.application.config.after_initialize doSpree.promotions.rules << Spree::Promotion::Rules::MinimumQuantityend```-Registered rules are discoverable at `/api/v3/admin/promotion_rules/types` together with their preference schema, and the dashboard's promotion editor is built on that endpoint — your rule appears there with a generated preferences form, no UI work needed.+### Step 3: Create the Admin Partial-### Step 3: Add Translations+Create a form partial so admins can configure the rule's preferences. The partial name must match the rule class name in underscore format:-The rule's display name and description in the dashboard come from your locale file:+```erb app/views/spree/admin/promotions/rules/_minimum_quantity.html.erb+<div class="row mb-3">+ <%= f.spree_number_field :preferred_quantity, label: Spree.t(:minimum_quantity) %>+</div>+```++### Step 4: Add Translations```yaml config/locales/en.ymlen:spree:+ minimum_quantity: Minimum Quantitypromotion_rule_types:minimum_quantity:name: Minimum Quantitydescription: Order must contain at least X items```+### Step 5: Restart and Test++After restarting your application, the new rule will be available in **Admin > Promotions** when adding rules to a promotion.+### Example: Rule with `actionable?`-When your rule targets specific line items (not the whole order), implement `actionable?` so that item-level actions only discount matching items:+When your rule targets specific line items (not the whole order), implement `actionable?` so that actions like `CreateItemAdjustments` only discount matching items:```ruby app/models/spree/promotion/rules/brand.rbmodule Spree@@ -117,7 +128,7 @@ module Spreepreference :brand_names, :array, default: []def applicable?(promotable)- promotable.is_a?(Spree::Order) || promotable.is_a?(Spree::Cart)+ promotable.is_a?(Spree::Order)enddef eligible?(order, options = {})@@ -143,17 +154,13 @@ end## Custom Promotion Actions-Actions define what happens when a promotion is applied. A discount action doesn't write rows itself — it declares **where** its discount belongs and **how much** it is, and Spree's promotion engine does the rest: running the competition between promotions, clamping amounts so nothing goes below zero, writing the winning Discount rows, and removing stale ones on every recalculation.+Actions define what happens when a promotion is applied. Most actions create [adjustments](/v5/developer/core-concepts/adjustments) on orders or line items.-### Discount Action (with Calculator)+### Step 1: Create the Action Class-Three declarations make a discount action:+#### Discount Action (with Calculator)-| Method | Description |-|--------|-------------|-| `discount_scope` | Where the discount belongs: `:line_item` (per matching item), `:fulfillment` (per delivery), or `:order` (whole order, distributed proportionally across items) |-| `compute_amount(adjustable)` | The discount for one adjustable — a line item, fulfillment, or the order, matching your scope. Return a **negative** amount, or zero for "no discount". |-| `perform(options = {})` | Called when the promotion is activated. For discount actions, delegate to `apply_via_adjuster(options)`. |+For actions that create monetary adjustments, include `Spree::CalculatedAdjustments` and `Spree::AdjustmentSource`:```ruby app/models/spree/promotion/actions/tiered_discount.rbmodule Spree@@ -161,15 +168,15 @@ module Spreemodule Actionsclass TieredDiscount < Spree::PromotionActioninclude Spree::CalculatedAdjustments+ include Spree::AdjustmentSourcebefore_validation -> { self.calculator ||= Calculator::FlatRate.new }- def discount_scope- :order- end-def perform(options = {})- apply_via_adjuster(options)+ order = options[:order]+ return false unless order.present?++ create_unique_adjustment(order, order)enddef compute_amount(order)@@ -180,7 +187,8 @@ module Spreeelse 0end- # Negative for discounts, capped at the order total+ # Must return negative amount for discounts+ # Cap at order total to prevent negative orders[discount, order.item_total].min * -1endend@@ -189,15 +197,9 @@ module Spreeend```-With `discount_scope :order`, the winning amount is shared out proportionally across the line items — you never handle the distribution yourself. With `:line_item`, `compute_amount` is called once per line item, and only items passing your rules' `actionable?` receive rows.--<Note>-There is nothing to clean up either. If the promotion stops being eligible — the cart shrinks below the threshold, the code is removed — the next recalculation deletes its rows. If your action loses to a better promotion, its candidate simply isn't written that round, and it competes again on the next one.-</Note>+#### Non-Discount Action-### Non-Discount Action--For actions that don't create discounts (awarding points, sending notifications), implement `perform` alone:+For actions that don't create adjustments (e.g., awarding points, sending notifications):```ruby app/models/spree/promotion/actions/add_loyalty_points.rbmodule Spree@@ -219,9 +221,45 @@ module Spreeend```-`perform` receives `:order` and `:promotion` in its options and should return `true` if the action was applied. Optionally implement `revert(options = {})` to undo side effects when the promotion is deactivated.+#### Key Methods to Implement++| Method | Required | Description |+|--------|----------|-------------|+| `perform(options = {})` | Yes | Called when the promotion is activated. `options` includes `:order` and `:promotion`. Return `true` if the action was applied. |+| `compute_amount(adjustable)` | For discount actions | Return the adjustment amount (negative for discounts). Cap at the adjustable's total to prevent negative amounts. |+| `revert(options = {})` | No | Called when a promotion is deactivated. Use to undo side effects (e.g., remove added line items). |++#### Available Helper Methods++When you include `Spree::AdjustmentSource`, you get:++```ruby+# Create a single adjustment (e.g., on the order)+create_unique_adjustment(order, adjustable)++# Create adjustments on multiple items (e.g., all line items)+create_unique_adjustments(order, order.line_items)++# With a filter block (e.g., only actionable line items)+create_unique_adjustments(order, order.line_items) do |line_item|+ promotion.line_item_actionable?(order, line_item)+end+```++When you include `Spree::CalculatedAdjustments`, you get:++```ruby+# Delegate to the calculator+compute(adjustable) # calls calculator.compute(adjustable)++# Set calculator by class name+self.calculator_type = 'Spree::Calculator::FlatRate'++# List available calculators for this action type+self.class.calculators+```-### Register and Translate+### Step 2: Register the Action```ruby config/initializers/spree.rbRails.application.config.after_initialize do@@ -229,6 +267,8 @@ Rails.application.config.after_initialize doend```+### Step 3: Add Translations+```yaml config/locales/en.ymlen:spree:@@ -238,43 +278,39 @@ en:description: Different discount amounts based on order total tiers```-Like rules, registered actions surface automatically in the dashboard's promotion editor via `/api/v3/admin/promotion_actions/types`.--## Custom Adjusters--Not every charge or reduction is a promotion. A gift wrap fee, a payment surcharge, or loyalty pricing has no rules, no coupon codes, and no competition — it just needs to be on the order whenever it applies. That's an **adjuster**: a class invoked on every recalculation that owns a family of [Fee or Discount](/v6/developer/core-concepts/taxes-discounts-fees) rows.--```ruby app/models/my_app/adjusters/gift_wrap.rb-module MyApp- module Adjusters- class GiftWrap < Spree::Adjusters::Base- def update- if order.gift_wrap?- order.fees.find_or_initialize_by(kind: 'gift_wrap').update!(- amount: 5.99, label: 'Gift wrapping'- )- else- order.fees.where(kind: 'gift_wrap').destroy_all- end- end- end- end-end-```--```ruby config/initializers/spree.rb-Rails.application.config.after_initialize do- Spree.adjusters << MyApp::Adjusters::GiftWrap-end+### Step 4: Restart and Test++After restarting, the new action will be available in **Admin > Promotions** when adding actions to a promotion.++## How Rules and Actions Work Together++Understanding how Spree evaluates promotions helps you build better custom rules and actions:++```mermaid+flowchart TD+ A[Order Updated] --> B[PromotionHandler::Cart]+ B --> C{For each promotion}+ C --> D{Check dates & usage}+ D -->|expired/exceeded| E[Deactivate]+ D -->|valid| F{Evaluate rules}+ F -->|match_policy: all| G[ALL rules must pass]+ F -->|match_policy: any| H[ANY rule must pass]+ G -->|eligible| I[Run actions]+ H -->|eligible| I+ G -->|ineligible| E+ H -->|ineligible| E+ I --> J[action.perform for each action]+ J --> K[Create adjustments]+ K --> L[Best promotion wins]```-The contract is one method: `update`. It runs on every recalculation, so it must be idempotent — write the rows that should exist, remove the ones that shouldn't (that's why the example uses `find_or_initialize_by` keyed by `kind` rather than `create`). The `order` it receives is the cart during checkout and the order after placement, and rows attach to it either way.--There's no totals bookkeeping to do: after all adjusters run, Spree re-sums the typed rows into the order totals and the tax provider estimates tax on the result — a fee you write here gets taxed in the same pass, like any other fee.--Custom discounts work the same way, writing `order.discounts` rows with your own `kind` (e.g. `'loyalty'`). Use a kind other than `'promotion'` — promotion rows belong to the promotion engine, which removes any it didn't write itself.+**Key points:**+- `match_policy: 'all'` means every rule must return `eligible? == true`+- `match_policy: 'any'` means at least one rule must return `eligible? == true`+- For item-level actions (`CreateItemAdjustments`), `actionable?(line_item)` on each rule filters which line items get the discount+- When multiple promotions compete, Spree picks the best one (largest discount) and marks others as ineligible-## Testing+## Testing Custom Rules and Actions```ruby spec/models/spree/promotion/rules/minimum_quantity_spec.rbrequire 'spec_helper'@@ -332,7 +368,7 @@ end## Related Documentation-- [Promotions](/v6/developer/core-concepts/promotions) — promotion architecture and built-in rules and actions-- [Taxes, Discounts & Fees](/v6/developer/core-concepts/taxes-discounts-fees) — the typed rows actions and adjusters write-- [Calculators](/developer/core-concepts/calculators) — available calculator types for promotion actions-- [Events](/developer/core-concepts/events) — subscribe to promotion events+- [Promotions](/v5/developer/core-concepts/promotions) - Promotion architecture and built-in rules/actions+- [Calculators](/v5/developer/core-concepts/calculators) - Available calculator types for promotion actions+- [Adjustments](/v5/developer/core-concepts/adjustments) - How adjustments work on orders and line items+- [Events](/v5/developer/core-concepts/events) - Subscribe to promotion eventsdiff --git a/docs/v5/developer/how-to/custom-report.mdx b/docs/v5/developer/how-to/custom-report.mdxnew file mode 100644index 0000000000..8da08300dc--- /dev/null+++ b/docs/v5/developer/how-to/custom-report.mdx@@ -0,0 +1,388 @@+---+title: Build a Custom Report+description: Step-by-step guide to creating custom reports with data queries, line item formatters, and CSV export.+canonical: "https://spreecommerce.org/docs/developer/how-to/custom-report"+---++## Overview++Spree's reporting system is designed for extension. Each report is a pair of classes — a **Report** that defines the data query and a **ReportLineItem** that formats each row — registered in `Spree.reports` so it appears in the admin UI.++This guide walks you through building a custom report from scratch, including advanced patterns for SQL aggregations and multi-vendor support.++Before starting, make sure you understand [how the reporting system works](/v5/developer/core-concepts/reports).++## Creating a Custom Report++### Step 1: Create the Report Class++Create a new report class inheriting from `Spree::Report`. The key method to implement is `line_items_scope`, which returns an `ActiveRecord::Relation` defining the records in your report:++```ruby app/models/spree/reports/customer_orders.rb+module Spree+ module Reports+ class CustomerOrders < Spree::Report+ # Define the scope of records to include in the report+ def line_items_scope+ store.orders.complete.where(+ completed_at: date_from..date_to,+ currency: currency+ ).includes(:user, :bill_address)+ end+ end+ end+end+```++The `line_items_scope` method has access to:++| Helper | Description |+|--------|-------------|+| `store` | The current store |+| `date_from` | Report start date |+| `date_to` | Report end date |+| `currency` | Report currency |+| `vendor` | Vendor (if multi-vendor is enabled) |++### Step 2: Create the Line Item Class++Create a corresponding line item class that transforms each record into report columns. The class name must match the report class name (e.g., `Reports::CustomerOrders` → `ReportLineItems::CustomerOrders`):++```ruby app/models/spree/report_line_items/customer_orders.rb+module Spree+ module ReportLineItems+ class CustomerOrders < Spree::ReportLineItem+ # Define attributes that will become columns+ attribute :order_number, :string+ attribute :completed_at, :string+ attribute :customer_email, :string+ attribute :customer_name, :string+ attribute :item_count, :integer+ attribute :total, :string++ # Map record fields to report columns+ def order_number+ record.number+ end++ def completed_at+ record.completed_at.strftime('%Y-%m-%d %H:%M')+ end++ def customer_email+ record.email+ end++ def customer_name+ record.bill_address&.full_name+ end++ def item_count+ record.line_items.sum(:quantity)+ end++ def total+ Spree::Money.new(record.total, currency: currency)+ end+ end+ end+end+```++**Important notes:**+- Use `attribute` to define columns with their types — these become CSV headers+- Each attribute needs a corresponding method that extracts/formats data from `record`+- `record` is a single item from `line_items_scope`+- Use `Spree::Money` for currency formatting+- `currency` and `store` are delegated from the report++#### Available Base Class Methods++`Spree::ReportLineItem` provides:++```ruby+# Returns column headers for display+self.headers+# => [{ name: :order_number, label: "Order Number" }, ...]++# Returns column names for CSV header row+self.csv_headers+# => ["order_number", "completed_at", "customer_email", ...]++# Converts line item to CSV row array+to_csv+# => ["R123456", "2025-01-15 14:30", "[email protected]", ...]+```++### Step 3: Register the Report++Add your report to the registry in an initializer:++```ruby config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.reports << Spree::Reports::CustomerOrders+end+```++### Step 4: Add Translations++Add the report name and column header translations:++```yaml config/locales/en.yml+en:+ spree:+ report_names:+ customer_orders: Customer Orders+ order_number: Order Number+ completed_at: Completed At+ customer_email: Customer Email+ customer_name: Customer Name+ item_count: Item Count+ total: Total+```++After restarting your application, the new report will be available in **Admin > Reports**.++## Advanced Patterns++### Complex Queries with Aggregations++For reports that aggregate data across records, use SQL directly in `line_items_scope`:++```ruby app/models/spree/reports/revenue_by_category.rb+module Spree+ module Reports+ class RevenueByCategory < Spree::Report+ def line_items_scope+ line_items_sql = Spree::LineItem+ .joins(:order)+ .where(+ spree_orders: {+ completed_at: date_from..date_to,+ currency: currency+ }+ )+ .select(+ "spree_line_items.variant_id",+ "SUM(spree_line_items.quantity) as quantity",+ "SUM(spree_line_items.pre_tax_amount) as revenue"+ )+ .group(:variant_id)+ .to_sql++ store.taxons+ .where(depth: 1) # Top-level categories+ .joins("LEFT JOIN spree_products_taxons ON spree_products_taxons.taxon_id = spree_taxons.id")+ .joins("LEFT JOIN spree_variants ON spree_variants.product_id = spree_products_taxons.product_id")+ .joins("LEFT JOIN (#{line_items_sql}) AS line_items ON line_items.variant_id = spree_variants.id")+ .select(+ "spree_taxons.*",+ "COALESCE(SUM(line_items.quantity), 0) AS total_quantity",+ "COALESCE(SUM(line_items.revenue), 0.0) AS total_revenue"+ )+ .group("spree_taxons.id")+ end+ end+ end+end+```++When using aggregated queries, the `record` in your line item class will have virtual attributes (like `total_quantity`, `total_revenue`) available as methods.++### Custom Summary Section++Override `summary` to provide aggregate metrics alongside the line items:++```ruby app/models/spree/reports/customer_orders.rb+module Spree+ module Reports+ class CustomerOrders < Spree::Report+ def summary+ {+ total_orders: line_items_scope.count,+ total_revenue: line_items_scope.sum(:total),+ average_order_value: line_items_scope.average(:total)+ }+ end+ end+ end+end+```++### Multi-Vendor Support++If you're using Spree Multi-Vendor, filter by vendor when one is selected:++```ruby app/models/spree/reports/vendor_sales.rb+module Spree+ module Reports+ class VendorSales < Spree::Report+ def line_items_scope+ scope = store.line_items.where(+ order: Spree::Order.complete.where(+ completed_at: date_from..date_to,+ currency: currency+ )+ )++ # Filter by vendor if one is selected+ scope = scope.where(vendor_id: vendor.id) if defined?(vendor) && vendor.present?++ scope+ end+ end+ end+end+```++## Testing Custom Reports++### Testing the Report Class++Test that your report's `line_items_scope` returns the correct records:++```ruby spec/models/spree/reports/customer_orders_spec.rb+require 'rails_helper'++RSpec.describe Spree::Reports::CustomerOrders, type: :model do+ let(:store) { create(:store) }+ let(:user) { create(:admin_user) }++ subject(:report) do+ described_class.new(+ store: store,+ user: user,+ currency: 'USD',+ date_from: 1.month.ago,+ date_to: Time.current+ )+ end++ describe '#line_items_scope' do+ let!(:completed_order) do+ create(:completed_order_with_totals, store: store, currency: 'USD', completed_at: 1.week.ago)+ end++ let!(:incomplete_order) do+ create(:order, store: store, currency: 'USD', state: 'cart')+ end++ let!(:other_currency_order) do+ create(:completed_order_with_totals, store: store, currency: 'EUR', completed_at: 1.week.ago)+ end++ let!(:old_order) do+ create(:completed_order_with_totals, store: store, currency: 'USD', completed_at: 2.months.ago)+ end++ it 'returns only completed orders within the date range and currency' do+ scope = report.line_items_scope++ expect(scope).to include(completed_order)+ expect(scope).not_to include(incomplete_order)+ expect(scope).not_to include(other_currency_order)+ expect(scope).not_to include(old_order)+ end+ end++ describe '#line_items' do+ let!(:order) do+ create(:completed_order_with_totals, store: store, currency: 'USD', completed_at: 1.week.ago)+ end++ it 'returns ReportLineItem objects' do+ items = report.line_items+ expect(items).to all(be_a(Spree::ReportLineItems::CustomerOrders))+ end++ it 'respects the limit option' do+ create(:completed_order_with_totals, store: store, currency: 'USD', completed_at: 2.days.ago)+ items = report.line_items(limit: 1)+ expect(items.length).to eq(1)+ end+ end+end+```++### Testing the ReportLineItem Class++Test that your line item correctly formats each record:++```ruby spec/models/spree/report_line_items/customer_orders_spec.rb+require 'rails_helper'++RSpec.describe Spree::ReportLineItems::CustomerOrders, type: :model do+ let(:store) { create(:store) }+ let(:user) { create(:admin_user) }+ let(:bill_address) { create(:address) }+ let(:order) do+ create(:completed_order_with_totals,+ store: store,+ currency: 'USD',+ completed_at: 1.week.ago,+ bill_address: bill_address)+ end++ let(:report) do+ Spree::Reports::CustomerOrders.new(+ store: store,+ user: user,+ currency: 'USD',+ date_from: 1.month.ago,+ date_to: Time.current+ )+ end++ subject(:line_item) { described_class.new(record: order, report: report) }++ describe '#order_number' do+ it 'returns the order number' do+ expect(line_item.order_number).to eq(order.number)+ end+ end++ describe '#customer_name' do+ it 'returns the billing address full name' do+ expect(line_item.customer_name).to eq(bill_address.full_name)+ end++ context 'when no billing address' do+ let(:bill_address) { nil }++ it 'returns nil' do+ order.update_column(:bill_address_id, nil)+ order.reload+ expect(line_item.customer_name).to be_nil+ end+ end+ end++ describe '#total' do+ it 'returns a Spree::Money formatted total' do+ result = line_item.total+ expect(result).to be_a(Spree::Money)+ expect(result.money.to_f).to eq(order.total.to_f)+ end+ end++ describe '#to_csv' do+ it 'returns an array of values for CSV row' do+ csv_row = line_item.to_csv+ expect(csv_row.length).to eq(6)+ expect(csv_row[0]).to eq(order.number)+ end+ end+end+```++### Key Testing Patterns++1. **Test scope filtering** — verify `line_items_scope` returns only records matching date range, currency, and store+2. **Test attribute formatting** — verify each attribute method returns correctly formatted data+3. **Test CSV output** — check `headers`, `csv_headers`, and `to_csv` return expected values+4. **Test edge cases** — handle nil values gracefully (e.g., missing addresses)++## Related Documentation++- [Reports](/v5/developer/core-concepts/reports) - Report architecture and built-in reports+- [Events](/v5/developer/core-concepts/events) - How report generation uses the events systemdiff --git a/docs/v5/developer/how-to/custom-search-provider.mdx b/docs/v5/developer/how-to/custom-search-provider.mdxnew file mode 100644index 0000000000..11992d878e--- /dev/null+++ b/docs/v5/developer/how-to/custom-search-provider.mdx@@ -0,0 +1,243 @@+---+title: Build a Custom Search Provider+description: Step-by-step guide to building a custom search provider for Spree, integrating external search engines like Typesense, Algolia, or Elasticsearch.+canonical: "https://spreecommerce.org/docs/developer/how-to/custom-search-provider"+---++## Overview++This guide walks you through building a custom search provider for Spree. By the end, you'll have a fully functional search integration that:++- Powers product search, filtering, sorting, and faceted navigation+- Handles multi-locale and multi-currency indexing automatically+- Integrates with the Store API without any frontend changes+- Supports background indexing and bulk reindex++Before starting, make sure you understand [how search and filtering works in Spree](/v5/developer/core-concepts/search-filtering).++<Info>+Spree ships with a built-in [Meilisearch provider](/integrations/search/meilisearch). If Meilisearch fits your needs, you don't need to build a custom provider — just configure it.+</Info>++## Architecture++```+Store API Request (locale=de, currency=EUR)+ │+ ├─ AR Scope (security + visibility)+ │ store.products.active(currency).accessible_by(ability)+ │+ └─ Search Provider (search + filter + facets)+ ├─ Database (default): ILIKE + Ransack + FiltersAggregator+ ├─ Meilisearch (built-in): one API call with locale/currency filtering+ └─ Your Provider: implements the same interface+```++The controller builds a base ActiveRecord scope for **security and visibility**, then delegates **everything else** to your search provider.++## Step 1: Create the Provider Class++Create a class that inherits from `Spree::SearchProvider::Base` and implements `search_and_filter`:++```ruby app/models/my_app/search_provider/typesense.rb+module MyApp+ module SearchProvider+ class Typesense < Spree::SearchProvider::Base+ # Enable background indexing jobs+ def self.indexing_required?+ true+ end++ def initialize(store)+ super+ require 'typesense'+ rescue LoadError+ raise LoadError, "Add `gem 'typesense'` to your Gemfile"+ end+ end+ end+end+```++`indexing_required?` returning `true` tells the `SearchIndexable` concern to enqueue background jobs when products are created, updated, or destroyed.++## Step 2: Implement `search_and_filter`++This is the core method. It receives a base AR scope (already filtered for security) and must return a `SearchResult`:++```ruby app/models/my_app/search_provider/typesense.rb+def search_and_filter(scope:, query: nil, filters: {}, sort: nil, page: 1, limit: 25)+ page = [page.to_i, 1].max+ limit = limit.to_i.clamp(1, 100)++ # 1. Query your search engine with locale/currency filtering+ results = client.collections[index_name].documents.search({+ q: query || '*',+ query_by: 'name,description,sku,option_values,category_names,tags',+ filter_by: build_filters(filters),+ sort_by: build_sort(sort),+ page: page,+ per_page: limit,+ facet_by: 'in_stock,price,category_ids,option_value_ids'+ })++ # 2. Extract product IDs (documents have composite IDs, extract product_id)+ product_ids = results['hits'].map { |h| h['document']['product_id'] }.uniq+ raw_ids = product_ids.filter_map { |pid| Spree::Product.decode_prefixed_id(pid) }++ # 3. Intersect with AR scope (safety net for authorization)+ products = raw_ids.any? ? scope.where(id: raw_ids).reorder(nil) : scope.none++ # 4. Build Pagy for pagination metadata+ require 'pagy'+ pagy = Pagy::Offset.new(count: results['found'], page: page, limit: limit)++ # 5. Return a SearchResult+ Spree::SearchProvider::SearchResult.new(+ products: products,+ filters: build_facet_response(results['facet_counts']),+ sort_options: %w[price -price name -name best_selling -available_on].map { |id| { id: id } },+ default_sort: 'manual',+ total_count: results['found'],+ pagy: pagy+ )+end+```++<Warning>+Always filter by `locale`, `currency`, `store_ids`, `status='active'`, and `discontinue_on` in your search engine — not just in the AR scope. This ensures pagination counts are accurate. The AR scope is a safety net, not the primary filter.+</Warning>++## Step 3: Implement Indexing++Products are indexed as **one document per market × locale** combination. The `ProductPresenter` handles this automatically:++```ruby app/models/my_app/search_provider/typesense.rb+def index(product)+ documents = Spree::SearchProvider::ProductPresenter.new(product, store).call+ documents.each do |doc|+ client.collections[index_name].documents.upsert(doc)+ end+end++def remove(product)+ remove_by_id(product.prefixed_id)+end++def remove_by_id(prefixed_id)+ # Delete all locale/currency variants of this product+ client.collections[index_name].documents.delete(+ filter_by: "product_id:=#{prefixed_id}"+ )+end+```++The `ProductPresenter` returns an array of documents. For a store with US (USD/English) and EU (EUR/German+French) markets, one product produces 3 documents — each with flat `name`, `price`, `locale`, `currency` fields.++## Step 4: Implement Bulk Reindex++Use `preload_associations_lazily` to avoid N+1 queries:++```ruby app/models/my_app/search_provider/typesense.rb+def reindex(scope = nil)+ scope ||= store.products+ ensure_index_settings!++ scope.reorder(id: :asc)+ .preload_associations_lazily+ .find_in_batches(batch_size: 500) do |batch|+ documents = batch.flat_map { |p| presenter_class.new(p, store).call }+ index_batch(documents)+ end+end++def index_batch(documents)+ client.collections[index_name].documents.import(documents, action: 'upsert')+end++def ensure_index_settings!+ # Create/update your collection schema here+end+```++<Info>+Use `flat_map` (not `map`) because `ProductPresenter#call` returns an array of documents per product.+</Info>++## Step 5: Register the Provider++```ruby config/initializers/spree.rb+Spree.search_provider = 'MyApp::SearchProvider::Typesense'+```++Then reindex:++```bash+rake spree:search:reindex+```++## Provider Contract Reference++| Method | Required | Description |+|--------|----------|-------------|+| `search_and_filter(scope:, query:, filters:, sort:, page:, limit:)` | Yes | Search, filter, sort, paginate, and return facets. Must return a `SearchResult`. |+| `self.indexing_required?` | Yes | Return `true` to enable background indexing jobs. |+| `index(product)` | Yes | Index a single product. `ProductPresenter#call` returns an array of documents. |+| `remove(product)` | Yes | Remove all locale/currency variants from the index. |+| `remove_by_id(prefixed_id)` | Yes | Remove by prefixed product ID (product may already be deleted). |+| `reindex(scope)` | Yes | Bulk reindex with `ensure_index_settings!` + batch indexing. |+| `index_batch(documents)` | Yes | Index a batch of pre-serialized documents. |+| `ensure_index_settings!` | No | Configure index schema. Called by `reindex` and rake task. |++### SearchResult++```ruby+Spree::SearchProvider::SearchResult.new(+ products: ar_relation, # ActiveRecord::Relation+ filters: [...], # Array of facet hashes+ sort_options: [{ id: 'price' }, ...], # Array of sort option objects+ default_sort: 'manual', # Default sort string+ total_count: 150, # Total before pagination+ pagy: pagy_object # Pagy::Offset or Pagy::Meilisearch+)+```++### ProductPresenter++```ruby+documents = Spree::SearchProvider::ProductPresenter.new(product, store).call+# => [+# { prefixed_id: "prod_abc_en_USD", product_id: "prod_abc", locale: "en",+# currency: "USD", name: "Blue Shirt", price: 29.99, ... },+# { prefixed_id: "prod_abc_de_EUR", product_id: "prod_abc", locale: "de",+# currency: "EUR", name: "Blaues Hemd", price: 27.50, ... }+# ]+```++### Indexing Lifecycle++The `Spree::SearchIndexable` concern on Product provides:++| Method | Description |+|--------|-------------|+| `product.add_to_search_index` | Index synchronously (inline) |+| `product.remove_from_search_index` | Remove synchronously (inline) |+| `product.search_presentation` | Preview the documents that would be indexed |+| `rake spree:search:reindex` | Bulk reindex all products |++Background jobs (`IndexJob`, `RemoveJob`) fire on `after_commit` when `indexing_required?` is `true`.++### Important: Prefixed IDs++Always use prefixed IDs (`ctg_abc`, `prod_xyz`, `optval_abc`) when indexing. Never use raw database IDs — Spree supports UUID primary keys.++### Metafield search schema++Product metafields marked `searchable` / `sortable` on `MetafieldDefinition` are projected through `Spree::SearchProvider::MetafieldSchema` — shared by providers and `ProductPresenter`. Toggle participation with definition flags; run `rake spree:search:reindex` after changes when using Meilisearch.++Document shaping for `cf_*` fields stays on `search_product_presenter` — the only search-related dependency.++## Related Documentation++- [Search & Filtering](/v5/developer/core-concepts/search-filtering) — Store API search reference+- [Meilisearch Integration](/integrations/search/meilisearch) — Built-in Meilisearch provider setupdiff --git a/docs/v5/developer/how-to/custom-stock-splitter.mdx b/docs/v5/developer/how-to/custom-stock-splitter.mdxnew file mode 100644index 0000000000..4f14aafbbb--- /dev/null+++ b/docs/v5/developer/how-to/custom-stock-splitter.mdx@@ -0,0 +1,214 @@+---+title: Build a Custom Stock Splitter+description: Step-by-step guide to extending Spree's stock splitter chain — break a location's allocation into multiple shipments along your own axis (refrigeration, gift wrap, bin size, hazmat, anything you need to physically separate).+canonical: "https://spreecommerce.org/docs/developer/how-to/custom-stock-splitter"+---++## Overview++When [Order Routing](/v5/developer/core-concepts/shipments#order-routing) picks one or more stock locations to fulfill an order, each location's allocation is then run through a chain of **splitters**. Each splitter looks at the packages produced so far and decides whether to break them further along its own axis.++Spree ships with four splitters out of the box (`ShippingCategory`, `Backordered`, `Digital`, `Weight`). You add your own when you need a *physical* separation that isn't expressed by any of the existing ones — refrigerated SKUs that can't share a box with ambient ones, hazmat goods that need their own carrier label, gift-wrap items that ship from a separate processing room, and so on.++Before starting, make sure you understand [how splitting works in Spree](/v5/developer/core-concepts/shipments#stock-splitters) and the [order routing](/v5/developer/core-concepts/shipments#order-routing) layer that runs before splitters.++| If the answer is "yes" | Pick |+|---|---|+| Should this affect _which_ locations fulfill the order? | A [routing rule](/v5/developer/how-to/custom-order-routing#custom-routing-rules), not a splitter |+| Does it just need to break one location's allocation into multiple physical packages? | A **splitter** |+| Should it apply to every location, every order? | A **splitter** registered globally |+| Should it apply only on certain channels or stores? | A **splitter** plus a guard inside `#split` |++### Splitters vs Order Routing — quick recap++Routing picks _which_ locations ship; splitters decide _how_ each location's packages are broken up. They live at different layers and never overlap:++| Layer | Decides | Sees | Output |+|---|---|---|---|+| Routing | Location order | All eligible locations + the whole order | Ranked location list |+| Splitter | Intra-location packaging | One location's packages so far | More (or fewer) packages |++A plugin can absolutely ship both — for example, a refrigerated-goods plugin might add a `RefrigeratedRouting::Rule` (prefer locations with cold storage) **and** a `RefrigeratedSplitter` (separate cold items from ambient items within each location). The two extension points are independent.++## Custom Stock Splitters++A splitter subclasses `Spree::Stock::Splitter::Base` and implements `#split(packages)`. The method receives an array of packages produced by the previous splitter (or the initial single-package output of `Packer#default_package`), returns an array of packages, and *must* call `return_next` so the chain continues.++### Step 1: Create the Splitter Class++```ruby app/models/spree/stock/splitter/refrigerated.rb+module Spree+ module Stock+ module Splitter+ class Refrigerated < Spree::Stock::Splitter::Base+ def split(packages)+ split_packages = packages.flat_map { |pkg| split_by_temperature(pkg) }+ return_next(split_packages)+ end++ private++ def split_by_temperature(package)+ grouped = package.contents.group_by { |item| item.variant.refrigerated? }+ grouped.values.map { |contents| build_package(contents) }+ end+ end+ end+ end+end+```++#### Key Method to Implement++| Method | Required | Description |+|--------|----------|-------------|+| `#split(packages)` | Yes | Receives the packages produced by the previous splitter, returns the new (possibly larger or smaller) array of packages. **Must call `return_next(packages)`** so the next splitter in the chain runs. |++#### Helpers Inherited from `Splitter::Base`++| Helper | Returns | When to use |+|---|---|---|+| `build_package(contents = [])` | A new `Spree::Stock::Package` for the splitter's `stock_location` | When you create a new package out of contents you've separated from an input package |+| `return_next(packages)` | The result of the next splitter, or `packages` if this is the last splitter | Always — at the end of `#split` |+| `stock_location` | The location the parent `Packer` is packing for | When you need to inspect or compare against the location |+| `packer` | The `Packer` instance | Rarely needed; available for advanced cases |++#### What `package.contents` Looks Like++Each `package.contents` is an array of `Spree::Stock::ContentItem` — wrappers around `InventoryUnit`. The two attributes you'll use most:++```ruby+content.variant # The Spree::Variant being shipped+content.inventory_unit # The Spree::InventoryUnit (gives access to line_item, order, etc.)+content.weight # Convenience: variant.weight × inventory_unit.quantity+content.state # :on_hand or :backordered+```++So the splitter's job is "look at each package's contents, decide which contents stay together, build new packages, return the chained result."++### Step 2: Register the Splitter++Splitters are registered globally on `Rails.application.config.spree.stock_splitters` — every order runs through the full chain. Add yours via an initializer:++```ruby config/initializers/spree.rb+Rails.application.config.to_prepare do+ Rails.application.config.spree.stock_splitters << Spree::Stock::Splitter::Refrigerated+end+```++The `to_prepare` block re-runs on Zeitwerk code reloads in development, so the splitter survives reloads correctly. Putting the line at the top of the initializer (outside `to_prepare`) works too in production but can leave a stale registry in development.++#### Replacing the Whole Chain++If you'd rather control the full chain (uncommon — the defaults are well-chosen), assign instead of append:++```ruby+Rails.application.config.spree.stock_splitters = [+ Spree::Stock::Splitter::ShippingCategory,+ Spree::Stock::Splitter::Refrigerated, # custom one slotted in+ Spree::Stock::Splitter::Backordered,+ Spree::Stock::Splitter::Digital+]+```++#### Ordering Matters++Splitters run in array order, each feeding the next. Two practical rules:++1. **Coarse before fine.** `ShippingCategory` runs first by default because it groups packages by carrier-relevant category before any other axis cuts in. Your custom splitter usually wants to run after it, unless you're separating items that should *never* share a package even within a category (e.g. hazmat).+2. **`Backordered` should usually be last among the "type" splitters.** It splits on-hand from backordered items, which is a state-axis split rather than a packaging-axis split. Splitting before `Backordered` gives you finer category buckets; splitting after does too — pick based on whether your axis applies to backorders. Refrigerated items have the same handling whether on-hand or backordered, so running before `Backordered` is fine. Hazmat shipping rules might differ between on-hand (real package) and backorder (paperwork only), so running after might be cleaner.++### Step 3: Test the Splitter++Splitter tests are unit tests — instantiate a fake `Packer`, hand the splitter a hand-built package, assert on the output. There's no factory required.++```ruby spec/models/spree/stock/splitter/refrigerated_spec.rb+require 'rails_helper'++RSpec.describe Spree::Stock::Splitter::Refrigerated, type: :model do+ let(:stock_location) { build_stubbed(:stock_location) }+ let(:packer) { instance_double(Spree::Stock::Packer, stock_location: stock_location) }+ let(:cold_variant) { build_stubbed(:variant).tap { |v| allow(v).to receive(:refrigerated?).and_return(true) } }+ let(:warm_variant) { build_stubbed(:variant).tap { |v| allow(v).to receive(:refrigerated?).and_return(false) } }++ let(:cold_item) { content_item_for(cold_variant) }+ let(:warm_item) { content_item_for(warm_variant) }++ subject(:splitter) { described_class.new(packer) }++ it 'splits a mixed package into a refrigerated package and an ambient package' do+ package = Spree::Stock::Package.new(stock_location, [cold_item, warm_item])++ result = splitter.split([package])++ expect(result.size).to eq(2)+ expect(result.flat_map { |p| p.contents.map(&:variant) }).to contain_exactly(cold_variant, warm_variant)+ end++ it 'leaves an all-cold package as a single package' do+ package = Spree::Stock::Package.new(stock_location, [cold_item])++ result = splitter.split([package])++ expect(result.size).to eq(1)+ expect(result.first.contents.map(&:variant)).to eq([cold_variant])+ end++ it 'returns chained packages unchanged when there is a next_splitter' do+ next_splitter = instance_double(Spree::Stock::Splitter::Base, split: [:done])+ splitter = described_class.new(packer, next_splitter)+ package = Spree::Stock::Package.new(stock_location, [cold_item, warm_item])++ expect(splitter.split([package])).to eq([:done])+ end++ def content_item_for(variant)+ inventory_unit = build_stubbed(:inventory_unit, variant: variant)+ Spree::Stock::ContentItem.new(inventory_unit, :on_hand)+ end+end+```++### Step 4 (optional): Add a Variant-side Predicate++The example above relies on `variant.refrigerated?`. In a real plugin you'd back that with a [Custom Field](/developer/core-concepts/custom-fields) on `Spree::Variant` — say a boolean metafield with key `refrigerated` — and define the predicate as a thin reader:++```ruby app/models/spree/variant_decorator.rb+Spree::Variant.class_eval do+ def refrigerated?+ metafields.find_by(namespace: 'logistics', key: 'refrigerated')&.value == 'true'+ end+end+```++This keeps the splitter pure and lets merchants flag SKUs from the admin UI without touching code.++### Common Pitfalls++- **Forgetting to call `return_next`.** If you return raw packages instead of `return_next(packages)`, every splitter after yours in the chain is silently skipped. The integration test will catch it; the unit test usually won't.+- **Building empty packages.** If you `group_by` and the group has no contents, `build_package([])` produces a package with no contents that downstream code may treat as a real package. Skip empty groups: `grouped.values.reject(&:empty?).map { |c| build_package(c) }`.+- **Mutating input packages in place.** A splitter should return new packages built from the contents of the inputs, not edit the originals — `Packer` and other splitters keep references. Use `build_package(contents)`, not `package.contents = ...`.+- **Doing routing-style work.** A splitter only sees one location's contents. If your logic needs to compare across locations ("ship the cheapest one first"), that's a routing rule or strategy, not a splitter.++## Coexistence with Order Routing++Splitters and routing run in series, not in parallel — every package a splitter sees comes from a single location that routing already chose. The interaction is purely top-down:++| Step | Layer | What runs |+|---|---|---|+| 1 | Routing | `Strategy::Rules#for_allocation` ranks all eligible locations |+| 2 | Per-location packing | One `Packer` per location runs the full splitter chain |+| 3 | Cross-location dedup | `Prioritizer.Adjuster` walks packages in rank order, assigns each inventory unit to the first package with on-hand stock |+| 4 | Rate estimation | `Estimator` attaches shipping rates |++Practical implications:++- **Splitter output feeds the Prioritizer.** A splitter that produces 3 packages from one location adds 3 candidates to the Prioritizer's pool. The Prioritizer keeps each unit in the highest-ranked package that still has it on hand and prunes empties.+- **Splitters can produce backordered-only packages.** That's fine — the `Backordered` splitter is the canonical example. The Prioritizer treats backordered packages as a fallback after exhausting on-hand options across all higher-ranked locations.+- **A splitter can't see which location ranked higher.** It runs per-location with no awareness of the rank. If you need rank-aware splitting (rare), do it in a custom strategy's `build_packages`, not a splitter.++## Next Steps++- [Shipments — Stock Splitters](/v5/developer/core-concepts/shipments#stock-splitters) — Concept overview and built-in splitter list+- [Build Custom Order Routing](/v5/developer/how-to/custom-order-routing) — The other layer of split-shipment customization+- [Custom Fields](/developer/core-concepts/custom-fields) — Tag variants with the data your splitter readsdiff --git a/docs/v5/developer/multi-tenant/configuration.mdx b/docs/v5/developer/multi-tenant/configuration.mdxnew file mode 100644index 0000000000..ebfaba3d87--- /dev/null+++ b/docs/v5/developer/multi-tenant/configuration.mdx@@ -0,0 +1,35 @@+---+title: Spree Multi Tenant Configuration+sidebarTitle: Configuration+description: Configure Spree multi-tenant SaaS deployments — set the app subdomain, reserved subdomains, tenant signup flow, and other initializer options.+canonical: "https://spreecommerce.org/docs/developer/multi-tenant/configuration"+---++Multi-tenant applications include additional configuration options. All configuration should be placed in `config/initializers/spree_multi_tenant.rb` file.++### App subdomain++Application subdomains is used to access the application, eg. `app.example.com`. By default for existing tenants it will redirect them to their tenant subdomain, eg. `store1.example.com`. If you want, you can also use this as a tenant signup/store setup page, this is available under `app.example.com/tenants/new`.++You can customize the app subdomain by:++```ruby+SpreeMultiTenant::Config[:app_subdomain] = 'admin'+```++This will change `app.example.com` to `admin.example.com`.++### Emails++Usually email providers, such as SendGrid, require emails to be send from a valid / verified email address, which will be your root domain.++```ruby+SpreeMultiTenant::Config[:mail_from_name] = ENV.fetch('MAIL_FROM_NAME', 'Your SaaS Name')+SpreeMultiTenant::Config[:mail_from_address] = ENV.fetch('MAIL_FROM_ADDRESS', "support@#{Spree.root_domain}")+```++<Info>+`mail_from_name` is only used in admin emails, such as admin staff invitations, exports, etc. For consumer facing emails, this will be your tenant store name, eg. `My Flower Store` (or whatever they set in the store settings).++Also, customer facing emails will use the tenant email address in `Reply-To` header.+</Info>diff --git a/docs/v5/developer/multi-tenant/core-concepts.mdx b/docs/v5/developer/multi-tenant/core-concepts.mdxnew file mode 100644index 0000000000..1b29b75a92--- /dev/null+++ b/docs/v5/developer/multi-tenant/core-concepts.mdx@@ -0,0 +1,91 @@+---+title: Multi-Tenant Core Concepts+sidebarTitle: Core Concepts+description: Understand the Spree multi-tenant architecture, including the Tenant class, row-level tenant isolation, tenanted models, and automatic seeding for new tenants.+canonical: "https://spreecommerce.org/docs/developer/multi-tenant/core-concepts"+---++## Tenant class++The center of the multi-tenant architecture is the `Spree::Tenant` class. This is the highest level class in the multi-tenant system.++Every tenanted model includes a `tenant_id` column. This is used to identify which tenant a record belongs to. It's row-level multi-tenancy.++After creating a new tenant it will automatically create store and run [Spree seeds](https://github.com/spree/spree/tree/main/core/app/services/spree/seeds) to populate data such as countries, zones, tax rates, etc.++## Tenanted models++All models that are tenanted inherit from `SpreeMultiTenant::Base` class. `spree_multi_tenant` automatically sets the `Spree.base_class` to `SpreeMultiTenant::Base` so all standard Spree models will be tenanted (with an exclusion of `Spree::CustomDomain`).++When creating a new model that you want to be tenanted remember to inherit from `SpreeMultiTenant::Base` and not from `Spree::Base` and add `tenant_id` column to the table, eg.++<CodeGroup>++```bash Spree CLI (Docker)+spree generate model Spree::NewModel tenant:references name:string --parent SpreeMultiTenant::Base+```++```bash Without Spree CLI+bin/rails g model Spree::NewModel tenant:references name:string --parent SpreeMultiTenant::Base+```++</CodeGroup>++<Info>+ You don't need to add `belongs_to :tenant` to the model, it's handled by gem.+</Info>++## Tenant selector++By default the current tenant is selected based on the subdomain or `Spree::CustomDomain`.++First it finds the current store, and later sets the current tenant based on the store's `tenant_id`.++Tenant record is accessible in views and controllers as `current_tenant`. In models you can access it via `SpreeMultiTenant.current_tenant`.++<Info>+ One tenant can have multiple stores. Calling `Spree::Store.default` will return the default store for the first tenant.+</Info>++## Code isolation++All code run when `SpreeMultiTenant.current_tenant` is set will be executed in the context of the tenant, what that means:++* all finder queries will always attach `tenant_id = <current_tenant.id>` to the query+* all writes will automatically set `tenant_id` to the current tenant ID (you don't need to do it manually)++<Warning>+ [insert_all](https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-insert_all) / [upsert_all](https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-upsert_all) methods will require you to manually set `tenant_id` to the desired value.+</Warning>++## Background jobs++Background jobs enqueued when `SpreeMultiTenant.current_tenant` is set will be executed in the context of the tenant.++## Enforce tenant context++Sometimes when you're not sure if the tenant context is active you can use `SpreeMultiTenant.with_tenant` to enforce it, eg.++```ruby+SpreeMultiTenant.with_tenant(tenant) do+ # all operations here will be executed in the context of the tenant+end+```++## Excluding tenant context++Sometimes you want to run a piece of code outside of the tenant context, for that you can use `SpreeMultiTenant.without_tenant`++```ruby+SpreeMultiTenant.without_tenant do+ # all operations here will be executed outside of the tenant context+end+```++## Command line++When using `bin/rails console` or `bin/rails runner` you can set the tenant context by:++```ruby+SpreeMultiTenant.current_tenant = Spree::Store.find_by(code: 'my_store').tenant+```diff --git a/docs/v5/developer/multi-tenant/quickstart.mdx b/docs/v5/developer/multi-tenant/quickstart.mdxnew file mode 100644index 0000000000..69c692e995--- /dev/null+++ b/docs/v5/developer/multi-tenant/quickstart.mdx@@ -0,0 +1,255 @@+---+title: Create a multi-tenant / SaaS platform on top of Spree+sidebarTitle: Quickstart+description: Set up Spree as a multi-tenant SaaS ecommerce platform — install the Enterprise gem, apply license keys, configure subdomains, and provision tenants.+canonical: "https://spreecommerce.org/docs/developer/multi-tenant/quickstart"+---++<Info>+ Multi-tenancy requires [Spree Enterprise Edition license](https://spreecommerce.org/pricing).+</Info>++Spree can be configured to run a multi-tenant / SaaS platform. This guide will walk you through the steps to set up your Spree application to support multiple tenants (stores).+Each tenant (store) can have its own isolated data and configuration, including:++* customer accounts+* staff accounts (admin users), staff can manage multiple tenants (it's the standard invitation flow)+* products, categories, and other catalog data+* orders and order history+* shipping and payment methods+* tax rates and zones+* store settings (name, logo, etc.)+* etc.++All data is fully isolated besides the staff users, which can manage multiple tenants. This allows you to create a SaaS platform where each tenant can have its own store with its own branding and configuration. Isolation works across admin dashboard and API.++<Info>+ If you need individual seller/supplier/vendor accounts but shared product listings under one site you should use [multi vendor recipe](/developer/multi-vendor) instead.+</Info>++## Prerequisites++* You need to be on Spree 5.1+, we recommend using [CLI](/developer/getting-started) to setup your Spree application.+* You need to set 2 environment variables in your `backend` directory:+ * `KEYGEN_ACCOUNT_ID`+ * `KEYGEN_LICENSE_KEY`+* Both PostgreSQL and MySQL are supported++<Info>+ You will need to add these environment variables to your CI/CD pipeline and staging/production environments.+</Info>++## Installation++### Eject the Spree backend++If you've created your project with `create-spree-app` you will need to eject the backend to be able to install the Enterprise and Multi-Tenant gems. You can do this by running:++```bash+spree eject+```++### Adding gems++1. Add the following code to your `backend/Gemfile`:++ ```ruby+ source "https://license:#{ENV['KEYGEN_LICENSE_KEY']}@rubygems.pkg.keygen.sh/#{ENV['KEYGEN_ACCOUNT_ID']}" do+ gem 'spree_enterprise'+ gem 'spree_multi_tenant'+ end+ ```++2. Configure the Docker image build to authenticate against the Keygen source.++ If you use the Spree CLI (Docker), `spree bundle install` resolves the licensed+ gems **inside the image at build time**, so the Keygen credentials must be available+ during `bundle install` in the `Dockerfile` — not just at runtime. Pass them as+ [BuildKit secrets](https://docs.docker.com/build/building/secrets/) so they are mounted+ as environment variables for the `bundle install` step only, and never baked into the+ image layers or history (unlike `ARG`/`ENV`/`COPY`).++ <Info>+ Skip this step if you install without the Spree CLI (plain `bundle install` on the host).+ In that case the Gemfile reads `KEYGEN_LICENSE_KEY` / `KEYGEN_ACCOUNT_ID` directly from+ your shell environment.+ </Info>++ Wrap **every** `bundle install` in your `backend/Dockerfile` with the secret mounts. There+ are usually two — one in the build stage and one in the dev stage:++ ```dockerfile backend/Dockerfile+ COPY .ruby-version Gemfile Gemfile.lock ./+ RUN bundle install # [!code --]+ RUN --mount=type=secret,id=keygen_license_key,env=KEYGEN_LICENSE_KEY,required=false \ # [!code ++]+ --mount=type=secret,id=keygen_account_id,env=KEYGEN_ACCOUNT_ID,required=false \ # [!code ++]+ bundle install # [!code ++]+ ```++ Then wire the secrets into **both** compose files (`docker-compose.yml` and+ `docker-compose.dev.yml` — the latter is what `spree eject` copies over) so the CLI+ supplies them to the build:++ ```yaml docker-compose.yml+ x-app: &app+ build:+ context: ./backend+ dockerfile: Dockerfile+ target: dev+ secrets: # [!code ++]+ - keygen_license_key # [!code ++]+ - keygen_account_id # [!code ++]++ # ...at the bottom of the file, declare where the secrets come from:+ secrets: # [!code ++]+ keygen_license_key: # [!code ++]+ environment: KEYGEN_LICENSE_KEY # [!code ++]+ keygen_account_id: # [!code ++]+ environment: KEYGEN_ACCOUNT_ID # [!code ++]+ ```++ <Info>+ Compose reads `environment:`-sourced secrets from the **shell environment** that runs+ the build, not from `.env`. Make sure `KEYGEN_LICENSE_KEY` and `KEYGEN_ACCOUNT_ID` are+ exported in the shell (and in your CI/CD and production build environments).+ </Info>++3. Install gems:++ <CodeGroup>++ ```bash Spree CLI (Docker)+ spree bundle install+ ```++ ```bash Without Spree CLI+ bundle install+ ```++ </CodeGroup>++4. Run generators:++ <CodeGroup>++ ```bash Spree CLI (Docker)+ spree generate spree_enterprise:install && spree generate spree_multi_tenant:install+ ```++ ```bash Without Spree CLI+ bin/rails g spree_enterprise:install && bin/rails g spree_multi_tenant:install+ ```++ </CodeGroup>++ <Info>+ This will copy and run migrations for `spree_enterprise` and `spree_multi_tenant` gems.+ The `spree_multi_tenant:install` generator also edits `config/routes.rb` (to add the+ tenant domain routing constraints), your customer user model, and your admin user model+ — see [Post-install configuration](#post-install-configuration) below.+ </Info>++## Post-install configuration++### Setting root domain++Usually multi-tenant applications are configured to use subdomains for each tenant. For example, if your root domain is `example.com`, you can have tenants like `tenant1.example.com`, `tenant2.example.com`, etc.+To make it work you need to set the `Spree.root_domain` in your `config/initializers/spree.rb` file, eg.++```ruby+Spree.root_domain = 'example.com'+```++or use environment variable:++```ruby+Spree.root_domain = ENV.fetch('SPREE_ROOT_DOMAIN', 'lvh.me')+```++You need to use `lvh.me` for local development, so cross-subdomain cookies will work, `localhost` will **not** work.++<Warning>+ `localhost` cannot be used as a cookie domain by browsers, so the session cookie set on+ `store1.localhost` is rejected and never sent back — you get logged out when moving between+ subdomains, and admin sign-in fails with `ActionController::InvalidAuthenticityToken`+ ("Can't verify CSRF token authenticity"). Use `lvh.me` (or `localtest.me`); both resolve to+ `127.0.0.1` and are valid cookie domains.+</Warning>++#### Sharing the session cookie across subdomains++For staff to stay signed in while moving between the app domain (`app.example.com`) and tenant+subdomains (`store1.example.com`), the session cookie must be scoped to the parent domain. Set+`COOKIE_TLD_LENGTH` to the number of labels in your root domain:++| Root domain | `COOKIE_TLD_LENGTH` | Cookie domain |+| ----------- | ------------------- | ------------- |+| `lvh.me` | `2` | `.lvh.me` |+| `example.com` | `2` | `.example.com` |+| `shop.example.co.uk` | `3` | `.example.co.uk` |++```bash .env+SPREE_ROOT_DOMAIN=lvh.me+COOKIE_TLD_LENGTH=2+```++#### Allowing tenant subdomains through host authorization++Rails' host authorization blocks unknown hosts. `.localhost` and `.test` are permitted in+development by default, but `.lvh.me` (and your production domain) are not — requests to+`app.lvh.me` are rejected with a "Blocked hosts" error until you allow them. Add your root+domain to `config/environments/development.rb`:++```ruby backend/config/environments/development.rb+if (root_domain = ENV['SPREE_ROOT_DOMAIN']).present?+ config.hosts << ".#{root_domain}"+end+```++### Customer User Class adjustment++We need to make slight adjustments to the user class so it can work in a multi-tenant environment.++The `spree_multi_tenant:install` generator adds `include SpreeMultiTenant::CustomerUserConcern`+to your customer user model automatically. You then need to **remove the `:validatable` module**+manually. `:validatable` validates the user's email uniqueness globally; the concern re-validates+it in the scope of the tenant instead, so the same email can exist across different tenants.++```ruby backend/app/models/spree/user.rb+class Spree::User < Spree.base_class+ include Spree::UserAddress+ include Spree::UserMethods+ include Spree::UserPaymentSource+ include SpreeMultiTenant::CustomerUserConcern # added by the generator++ devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable # [!code --]+ devise :database_authenticatable, :registerable, :recoverable, :rememberable # [!code ++]+end+```++<Warning>+ Only remove `:validatable`. Do not add other Devise modules (such as `:confirmable`) here+ unless your app is already set up for them — `:confirmable`, for example, requires additional+ columns and a confirmation flow, and adding it will break sign-in.+</Warning>++### Admin User Class adjustment++The generator also changes your admin user model's base class from `Spree.base_class` to+`Spree::Base`. If your `admin_user.rb` exists, this is applied automatically; otherwise make the+change yourself:++```ruby backend/app/models/spree/admin_user.rb+class Spree::AdminUser < Spree.base_class # [!code --]+class Spree::AdminUser < Spree::Base # [!code ++]+ include Spree::AdminUserMethods++ devise :database_authenticatable, :registerable,+ :recoverable, :rememberable, :validatable+end+```++<Info>+ Unlike the customer user model, the admin user model keeps `:validatable` — staff accounts are+ global and can manage multiple tenants, so their emails remain globally unique.+</Info>diff --git a/docs/developer/multi-vendor/installation.mdx b/docs/v5/developer/multi-vendor/installation.mdxsimilarity index 95%rename from docs/developer/multi-vendor/installation.mdxrename to docs/v5/developer/multi-vendor/installation.mdxindex 36eee8aa60..74ecbf9b8f 100644--- a/docs/developer/multi-vendor/installation.mdx+++ b/docs/v5/developer/multi-vendor/installation.mdx@@ -2,6 +2,7 @@title: Spree Multi Vendor InstallationsidebarTitle: Installationdescription: Install and configure Spree Multi-Vendor to launch a marketplace with multiple vendors, including prerequisites, gem setup, license keys, and vendor onboarding.+canonical: "https://spreecommerce.org/docs/v5/developer/multi-vendor/installation"---<Warning>diff --git a/docs/developer/multi-vendor/quickstart.mdx b/docs/v5/developer/multi-vendor/quickstart.mdxsimilarity index 93%rename from docs/developer/multi-vendor/quickstart.mdxrename to docs/v5/developer/multi-vendor/quickstart.mdxindex 8aa18aa75b..db9b7d4086 100644--- a/docs/developer/multi-vendor/quickstart.mdx+++ b/docs/v5/developer/multi-vendor/quickstart.mdx@@ -1,6 +1,7 @@---title: Building a Multi-Vendor Marketplace with SpreesidebarTitle: Quickstart+canonical: "https://spreecommerce.org/docs/v5/developer/multi-vendor/quickstart"---If you want to have a true multi-vendor marketplace, you will need to purchase [Enterprise Edition license](https://spreecommerce.org/pricing) which includes `spree_multi_vendor` gem providing full multi-vendor support.diff --git a/docs/v5/developer/sdk/admin/authentication.mdx b/docs/v5/developer/sdk/admin/authentication.mdxnew file mode 100644index 0000000000..3c3cf9851b--- /dev/null+++ b/docs/v5/developer/sdk/admin/authentication.mdx@@ -0,0 +1,112 @@+---+title: "Admin SDK authentication with API keys and JWT cookies"+sidebarTitle: "Authentication"+description: "Authenticate @spree/admin-sdk with a secret API key for server-to-server, scope-based access or JWT cookie auth for role-based browser admin apps."+canonical: "https://spreecommerce.org/docs/developer/sdk/admin/authentication"+---++The Admin API supports two authentication methods. Both reach the same endpoints — they differ in **where the credential lives** and **how authorization is decided**:++| | Secret API key | JWT + cookie |+|---|---|---|+| **For** | Backend integrations, automations, cron jobs | Browser-based admin apps where a human signs in |+| **Credential** | `sk_…` key, created in the admin | Short-lived access token + httpOnly refresh cookie |+| **Authorization** | [Scopes](/api-reference/admin-api/authentication) attached to the key (`read_products`, `write_orders`, …) | The admin user's roles and permissions |+| **Where it runs** | Server-side only — never in a browser | Browser (the refresh token never touches your JS) |++## Secret API key (server-to-server)++Create a secret key in the admin under **Settings → API Keys**, grant it the scopes your integration needs, and pass it to the client:++```typescript+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: process.env.SPREE_SECRET_KEY, // sk_xxx+})+```++Each key carries the list of scopes granted at creation time. A request to an endpoint the key isn't scoped for fails with `code: 'access_denied'` — the error's `details.required_scope` names the missing scope (see [Querying & Errors](/v5/developer/sdk/admin/querying-and-errors#scope-errors)).++<Warning>+ Secret keys grant back-office access to your store. Never embed them in client-side code, mobile apps, or public repositories — keep them in server-side environment variables or a secrets manager.+</Warning>++## JWT + cookie authentication (browser apps)++For browser-based admin tooling, authenticate as an admin user. The flow is designed so that **no long-lived credential is ever exposed to JavaScript**:++- `auth.login()` returns `{ token, user }` — a short-lived access token you hold in memory.+- The **refresh token never appears in JSON.** The server sets it as an `HttpOnly` cookie scoped to `/api/v3/admin/auth`, and the SDK sends requests with `credentials: 'include'` by default, so the cookie flows automatically.+- `auth.refresh()` takes **no arguments** — it's driven entirely by the cookie, and rotates it on every call.+- `auth.logout()` revokes the refresh token server-side and clears the cookie.++```typescript+import { createAdminClient } from '@spree/admin-sdk'++// A cookie-auth app can start with no credentials at all+const client = createAdminClient({ baseUrl: 'https://your-store.com' })++// Sign in — the refresh token lands in the httpOnly cookie+const { token, user } = await client.auth.login({+ email: '[email protected]',+ password: 'password123',+})+client.setToken(token)++// Auto-recover from expired access tokens+client.onUnauthorized(async () => {+ const { token: fresh } = await client.auth.refresh()+ client.setToken(fresh)+ return true // retry the failed request+})++// Sign out — revokes the refresh token server-side+await client.auth.logout()+```++### Bootstrapping a returning session++Because the refresh cookie outlives the in-memory access token, a returning user can be signed back in without re-entering credentials — call `refresh()` on app load and treat failure as "not signed in":++```typescript+try {+ const { token } = await client.auth.refresh()+ client.setToken(token)+} catch {+ // No valid session — show the login form+}+```++### Identity providers++`auth.login()` also accepts third-party identity-provider payloads when the server has a [matching strategy registered](/v5/developer/how-to/custom-api-authentication):++```typescript+const { token } = await client.auth.login({ provider: 'auth0', token: idpJwt })+```++### Current user and permissions++After signing in, `client.me.get()` returns the admin user's profile together with their serialized permissions — use it to drive what your UI shows:++```typescript+const { user, permissions } = await client.me.get()+```++## Staff invitations++The `auth` resource also exposes the unauthenticated invitation-acceptance flow used when onboarding new staff: `auth.lookupInvitation(id, token)` returns the safe-to-render invitation context (store, role, inviter), and `auth.acceptInvitation(id, token, params)` accepts it — issuing a JWT and refresh cookie identical to `login`. Sending invitations is an authenticated operation on [`client.invitations`](/v5/developer/sdk/admin/resources).++## Custom fetch++Pass a custom `fetch` implementation when you need request interception, proxying, or a non-standard runtime:++```typescript+const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: process.env.SPREE_SECRET_KEY,+ fetch: customFetchImplementation,+})+```diff --git a/docs/v5/developer/sdk/admin/extending.mdx b/docs/v5/developer/sdk/admin/extending.mdxnew file mode 100644index 0000000000..a9ced92c65--- /dev/null+++ b/docs/v5/developer/sdk/admin/extending.mdx@@ -0,0 +1,71 @@+---+title: Custom Admin Endpoints+sidebarTitle: Custom Endpoints+description: Call custom Admin API endpoints using the SDK's built-in request method+canonical: "https://spreecommerce.org/docs/developer/sdk/admin/extending"+---++The Admin SDK client exposes a `request` method — the same function that powers `client.products.list()`, `client.orders.get()`, and every other built-in resource. Use it to call any Admin API endpoint, including ones added by an extension gem that doesn't ship its own client.++```typescript+import { createAdminClient } from '@spree/admin-sdk'+import type { PaginatedResponse } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://api.mystore.com',+ token: 'sk_YOUR_SECRET_KEY', // or a JWT from /auth/login+})++interface Brand {+ id: string+ name: string+ slug: string | null+ description: string | null+ logo_url: string | null+}++// Paths are relative to /api/v3/admin+const brands = await client.request<PaginatedResponse<Brand>>('GET', '/brands')+const brand = await client.request<Brand>('GET', '/brands/brand_2X9aQf7kEw')+```++`client.request` uses the same auth headers (secret API key *or* JWT, whichever was configured at client creation), retry logic, and base URL as every other resource on the client. The 401 → refresh → retry handshake that's wired up for the dashboard's user session applies to your custom endpoint too.++## Mutations++POST/PATCH/DELETE work the same way — pass `{ body }` for the request payload:++```typescript+const created = await client.request<Brand>('POST', '/brands', {+ body: { name: 'Acme', slug: 'acme', description: 'Quality goods since 1953' },+})++const updated = await client.request<Brand>('PATCH', `/brands/${created.id}`, {+ body: { description: 'New tagline' },+})++await client.request<void>('DELETE', `/brands/${created.id}`)+```++## Ransack filters and pagination++Standard list params work — pass them as the third argument's `params`:++```typescript+const result = await client.request<PaginatedResponse<Brand>>('GET', '/brands', {+ params: {+ page: 2,+ limit: 25,+ filter: { name_cont: 'nike' },+ sort: '-created_at',+ },+})+```++The SDK transforms `filter`/`sort` into the Ransack-flavored query string the Admin API expects (`q[name_cont]=nike&q[s]=created_at%20desc`) automatically — same behavior as `client.products.list({ filter: ... })`.++## See also++- The [Store SDK extending guide](/v5/developer/sdk/extending) covers the same pattern for storefront endpoints — the API is identical, only the base path (`/api/v3/store`) and auth header differ.+- The [API](/v5/developer/tutorial/api) and [SDK](/v5/developer/tutorial/sdk) tutorials walk through creating new Spree endpoints end-to-end (Rails controller, serializer, TypeScript types). Everything they show for the Store API applies equivalently for the Admin API.+- For building dashboard UI on top of your custom endpoint, see the [Dashboard](/v5/developer/dashboard/overview) section — start with [Customization Quickstart](/v5/developer/dashboard/customization/quickstart) for in-app changes or [Plugin Overview](/v5/developer/dashboard/plugins/overview) for redistributable packages.diff --git a/docs/v5/developer/sdk/admin/querying-and-errors.mdx b/docs/v5/developer/sdk/admin/querying-and-errors.mdxnew file mode 100644index 0000000000..c2f3f4bea8--- /dev/null+++ b/docs/v5/developer/sdk/admin/querying-and-errors.mdx@@ -0,0 +1,133 @@+---+title: "Filtering, pagination, and error handling in the Admin SDK"+sidebarTitle: "Querying & Errors"+description: "Filter, sort, paginate, and expand Admin API collections with flat Ransack parameters and handle structured SpreeError responses from @spree/admin-sdk."+canonical: "https://spreecommerce.org/docs/developer/sdk/admin/querying-and-errors"+---++## Filtering++Collection endpoints support [Ransack](https://activerecord-hackery.github.io/ransack/) filters passed as **flat parameters** — append a predicate suffix to any filterable attribute. The SDK wraps filter keys in `q[…]` automatically:++```typescript+const { data: orders } = await client.orders.list({+ status_eq: 'complete', // exact match+ total_gteq: 100, // greater than or equal+ email_cont: '@example.com', // substring match+ user_id_eq: 'cus_xxx', // prefixed IDs work directly+ sort: '-completed_at',+ page: 2,+ limit: 50,+})+```++Common predicates: `_eq`, `_not_eq`, `_cont` (contains), `_start`, `_end`, `_gteq` / `_lteq`, `_gt` / `_lt`, `_in` (array), `_null`. The filterable attributes per resource are listed in the [Admin API reference](/api-reference/admin-api/introduction); each model declares an explicit allowlist, so unknown filter keys are ignored rather than executed.++<Note>+ Foreign-key predicates accept **prefixed IDs** (`user_id_eq: 'cus_xxx'`, `variant_id_in: ['variant_a', 'variant_b']`) — the API translates them; you never handle raw database IDs.+</Note>++## Sorting++Pass `sort` with an attribute name; prefix with `-` for descending. Comma-separate multiple fields:++```typescript+await client.products.list({ sort: '-updated_at,name' })+```++## Pagination++List responses return `{ data, meta }`. Drive pagination with `page` and `limit`:++```typescript+const { data, meta } = await client.products.list({ page: 1, limit: 50 })++meta.count // total records+meta.pages // total pages+meta.next // next page number, or null on the last page+meta.previous // previous page number, or null on the first+```++A simple fetch-all loop:++```typescript+let page: number | null = 1+while (page) {+ const { data, meta } = await client.products.list({ page, limit: 100 })+ process(data)+ page = meta.next+}+```++## Expanding associations++Pass `expand` to embed related records in the response, instead of making follow-up requests. Dot notation reaches nested associations (up to 4 levels):++```typescript+const order = await client.orders.get('order_xxx', {+ expand: ['items', 'customer', 'fulfillments.items'],+})++const products = await client.products.list({+ expand: ['variants', 'variants.media'],+})+```++`fields` does the opposite — trims the response to just the attributes you name (`id` is always included):++```typescript+await client.products.list({ fields: ['name', 'slug', 'status'] })+```++## Error handling++Every non-2xx response throws a `SpreeError` with a stable machine-readable `code`, the HTTP `status`, and optional structured `details`:++```typescript+import { SpreeError } from '@spree/admin-sdk'++try {+ await client.orders.update(orderId, { email })+} catch (err) {+ if (err instanceof SpreeError) {+ err.code // e.g. 'validation_error', 'record_not_found', 'access_denied'+ err.status // e.g. 422+ err.message // human-readable summary+ err.details // optional structured context+ }+}+```++### Validation errors++On `422` responses, `details` maps attribute names to arrays of messages — ready to project onto form fields:++```typescript+try {+ await client.products.create({ name: '' })+} catch (err) {+ if (err instanceof SpreeError && err.status === 422) {+ err.details // { name: ["can't be blank"] }+ }+}+```++### Scope errors++When a request fails because the secret API key lacks the required [scope](/v5/developer/sdk/admin/authentication), the error has `code: 'access_denied'` and `details.required_scope` names the missing scope:++```typescript+catch (err) {+ if (err instanceof SpreeError && err.code === 'access_denied') {+ console.error(`API key is missing scope: ${err.details?.required_scope}`)+ }+}+```++### Expired JWT sessions++For cookie-authenticated apps, register an `onUnauthorized` handler to transparently refresh and retry on `401` — see [Authentication](/v5/developer/sdk/admin/authentication#jwt--cookie-authentication-browser-apps).++## Retries++The SDK retries failed idempotent requests (GET/HEAD, plus requests carrying an idempotency key) with exponential backoff and jitter — transient network errors and retryable statuses recover without any code on your side.diff --git a/docs/v5/developer/sdk/admin/quickstart.mdx b/docs/v5/developer/sdk/admin/quickstart.mdxnew file mode 100644index 0000000000..9419a5cba4--- /dev/null+++ b/docs/v5/developer/sdk/admin/quickstart.mdx@@ -0,0 +1,84 @@+---+title: "Admin SDK quickstart for @spree/admin-sdk"+sidebarTitle: Quickstart+description: "Install and configure @spree/admin-sdk, the official TypeScript client for the Spree Admin API v3, to manage products, orders, customers, and stock."+canonical: "https://spreecommerce.org/docs/developer/sdk/admin/quickstart"+---++[`@spree/admin-sdk`](https://www.npmjs.com/package/@spree/admin-sdk) is the official TypeScript SDK for the [Admin API v3](/api-reference/admin-api/introduction) — the back-office counterpart to [`@spree/sdk`](/v5/developer/sdk/quickstart). Use it to build integrations, automations, internal tools, and custom admin UIs: manage products, orders, customers, stock, promotions, webhooks, and more.++<Warning>+ The Admin SDK is in **Developer Preview** on the `0.x` line and published under the `next` dist-tag. The API surface may change between minor versions — check the [changelog](https://github.com/spree/spree/blob/main/packages/admin-sdk/CHANGELOG.md) when updating. It requires Spree 5.5 or newer.+</Warning>++## Installation++```bash+npm install @spree/admin-sdk@next+```++## Quick start++Create a client with a [secret API key](/v5/developer/sdk/admin/authentication) (server-to-server) and start calling resources:++```typescript+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: process.env.SPREE_SECRET_KEY, // sk_xxx — server-side only+})++// List recent completed orders+const { data: orders, meta } = await client.orders.list({+ status_eq: 'complete',+ sort: '-completed_at',+ limit: 25,+})++// Create a purchasable product — pricing lives on variants+const product = await client.products.create({+ name: 'Aero Hoodie',+ status: 'active',+ tags: ['new-arrivals'],+ variants: [+ {+ sku: 'AERO-HOODIE',+ prices: [{ currency: 'USD', amount: '59.00' }],+ },+ ],+})+```++Every method is fully typed — responses use types generated from the API serializers:++```typescript+import type { Order, PaginatedResponse } from '@spree/admin-sdk'++const page: PaginatedResponse<Order> = await client.orders.list()+```++<Note>+ Secret keys grant back-office access — never ship them in browser code. For browser-based admin apps, use [JWT cookie authentication](/v5/developer/sdk/admin/authentication#jwt--cookie-authentication-browser-apps) instead.+</Note>++## Learn more++<CardGroup cols={2}>+ <Card title="Authentication" icon="key" href="/developer/sdk/admin/authentication">+ Secret keys with scopes for servers, JWT + httpOnly refresh cookie for browser apps.+ </Card>+ <Card title="Resources" icon="boxes" href="/developer/sdk/admin/resources">+ The full resource map — products, orders, customers, stock, promotions, webhooks, and more.+ </Card>+ <Card title="Querying & Errors" icon="filter" href="/developer/sdk/admin/querying-and-errors">+ Filtering, sorting, pagination, prefixed IDs, and structured error handling.+ </Card>+ <Card title="Admin API Reference" icon="book" href="/api-reference/admin-api/introduction">+ The underlying REST API the SDK wraps — every endpoint, parameter, and response shape.+ </Card>+</CardGroup>++<Tip>+ Adding your own resources? The [`spree generate api_resource`](/v5/developer/tutorial/api) generator scaffolds Admin API endpoints (model, serializers, controllers, specs) in one command, and the [extending guide](/v5/developer/sdk/extending) shows how to call custom endpoints from the SDK.+</Tip>diff --git a/docs/v5/developer/sdk/admin/resources.mdx b/docs/v5/developer/sdk/admin/resources.mdxnew file mode 100644index 0000000000..e734e11806--- /dev/null+++ b/docs/v5/developer/sdk/admin/resources.mdx@@ -0,0 +1,129 @@+---+title: "Admin SDK resources and CRUD client methods"+sidebarTitle: "Resources"+description: "Reference for every @spree/admin-sdk resource — products, orders, customers, inventory, pricing, promotions, store configuration, and platform clients."+canonical: "https://spreecommerce.org/docs/developer/sdk/admin/resources"+---++Every Admin API resource is exposed as a property on the client (`client.orders`, `client.products`, …). Collection resources follow a consistent CRUD shape — `list`, `get`, `create`, `update`, `delete` — plus resource-specific actions. Nested resources take the **parent ID as the first argument**:++For the underlying HTTP surface — every endpoint with the API key scope it requires — see the [Admin API endpoint index](/api-reference/admin-api/endpoints).++```typescript+// Top-level+const order = await client.orders.get('order_xxx')++// Nested — parent ID first+const payments = await client.orders.payments.list('order_xxx')+await client.orders.payments.capture('order_xxx', 'payment_xxx')++// Nested create+await client.customers.addresses.create('cus_xxx', {+ first_name: 'Jane',+ last_name: 'Doe',+ address1: '350 Fifth Avenue',+ city: 'New York',+ postal_code: '10118',+ country_iso: 'US',+ state_abbr: 'NY',+ is_default_shipping: true,+})+```++## Catalog++| Client | Endpoints |+|---|---|+| `client.products` | CRUD, `clone`, and bulk operations (`bulkStatusUpdate`, `bulkAddToCategories` / `bulkRemoveFromCategories`, `bulkAddToChannels` / `bulkRemoveFromChannels`, `bulkAddTags` / `bulkRemoveTags`, `bulkDestroy`). Nested: `media`, `variants` (with their own `media`). |+| `client.variants` | Top-level variant search across products (`list`, `get`). |+| `client.optionTypes` | CRUD on option types and their values. |+| `client.categories` | List categories. |+| `client.tags` | Autocomplete tag names per taggable type. |+| `client.taxCategories` | CRUD on tax categories. |++## Orders & fulfillment++| Client | Endpoints |+|---|---|+| `client.orders` | List, get, create, update, delete, `complete`, `cancel`, `approve`, `resume`, `resendConfirmation`. Nested: `items`, `payments` (incl. `capture` / `void`), `fulfillments` (incl. `fulfill` / `cancel` / `resume` / `split`), `refunds`, `giftCards`, `storeCredits`, `adjustments`. |++## Customers++| Client | Endpoints |+|---|---|+| `client.customers` | CRUD plus bulk group operations (`bulkAddToGroups` / `bulkRemoveFromGroups`) and bulk tags. Nested: `addresses`, `creditCards`, `storeCredits`. |+| `client.customerGroups` | CRUD on customer groups. |++## Pricing & promotions++| Client | Endpoints |+|---|---|+| `client.prices` | CRUD plus `bulkUpsert` / `bulkDestroy` for variant prices. |+| `client.priceLists` | CRUD, `activate` / `deactivate`, and price-list rule types. |+| `client.promotions` | CRUD. Nested: `actions`, `rules`, `couponCodes`. |+| `client.promotionActions` | Lookup of available action `types` and `calculators`. |+| `client.promotionRules` | Lookup of available rule `types`. |+| `client.giftCards` | CRUD on gift cards. |+| `client.giftCardBatches` | List, get, and create gift card batches. |++## Inventory++| Client | Endpoints |+|---|---|+| `client.stockLocations` | CRUD on stock locations. |+| `client.stockItems` | List, get, update, delete stock items. |+| `client.stockTransfers` | List, get, create, delete stock transfers. |++## Sales channels++| Client | Endpoints |+|---|---|+| `client.channels` | CRUD plus `addProducts` / `removeProducts`. |+| `client.markets` | CRUD on markets. |++## Store configuration++| Client | Endpoints |+|---|---|+| `client.store` | Store profile (`get`, `update`). |+| `client.paymentMethods` | CRUD plus `types` (available gateway types). |+| `client.countries` | List and read countries (for address dropdowns). |+| `client.customFieldDefinitions` | CRUD on [custom field](/v5/developer/core-concepts/metafields) definitions. |+| `client.exports` | Create and track CSV exports (products, orders, customers, …). |+| `client.directUploads` | Pre-signed Active Storage uploads (used by media flows). |++## Platform & access++| Client | Endpoints |+|---|---|+| `client.auth` | Login (email/password or identity provider), cookie-driven refresh, logout, invitation lookup/acceptance — see [Authentication](/v5/developer/sdk/admin/authentication). |+| `client.me` | Current admin user + permissions. |+| `client.adminUsers` | List, get, update, delete admin users. |+| `client.invitations` | Staff invitations — list, get, create, delete, `resend`. |+| `client.roles` | List and read roles. |+| `client.apiKeys` | CRUD plus `revoke` for API keys. |+| `client.allowedOrigins` | CRUD on CORS allowed origins. |+| `client.webhookEndpoints` | CRUD, `sendTest`, `enable` / `disable`. Nested: `deliveries` (list, get, `redeliver`). |+| `client.dashboard` | Sales analytics. |++## Custom fields++Resources that support [custom fields](/v5/developer/core-concepts/metafields) (products, variants, orders, customers, categories, option types) expose a `customFields` accessor taking the parent ID first:++```typescript+await client.products.customFields.list('prod_xxx')+await client.products.customFields.create('prod_xxx', {+ custom_field_definition_id: 'cfd_xxx',+ value: 'limited-edition',+})+```++The generic escape hatch covers any owner type:++```typescript+await client.customFields('Spree::Product', 'prod_xxx').list()+```++## Adding your own resources++The resource map grows with your store. The [`spree generate api_resource`](/v5/developer/tutorial/api) generator scaffolds new Admin API endpoints (model, serializers, controllers, routes, specs) in one command — then call them from the SDK with a [custom fetch or raw request](/v5/developer/sdk/extending), or generate a typed client for them.diff --git a/docs/v5/developer/sdk/authentication.mdx b/docs/v5/developer/sdk/authentication.mdxnew file mode 100644index 0000000000..5378b15fb9--- /dev/null+++ b/docs/v5/developer/sdk/authentication.mdx@@ -0,0 +1,63 @@+---+title: Authentication+description: Authentication modes and guest checkout with the Spree SDK+canonical: "https://spreecommerce.org/docs/developer/sdk/authentication"+---++import SdkClientSetup from '/snippets/store-api/sdk-client-setup.mdx'+import AuthJwtExample from '/snippets/store-api/auth-jwt-example.mdx'+import AuthGuestCart from '/snippets/store-api/auth-guest-cart.mdx'++The SDK supports multiple authentication modes depending on your use case. For a full overview of the API authentication methods, see the [Store API Authentication](/api-reference/store-api/authentication) reference.++## Publishable Key Only (Guest/Public Access)++Use a publishable API key for public endpoints like browsing products:++<SdkClientSetup />++```typescript+// Public endpoints work without user authentication+const products = await client.products.list()+```++## Publishable Key + JWT (Authenticated Customer)++For authenticated customer actions like viewing orders or managing addresses:++<AuthJwtExample />++```typescript+// Refresh token when needed+const newTokens = await client.auth.refresh({ token })+```++## Register New Customer++```typescript+const { token, user } = await client.customers.create({+ email: '[email protected]',+ password: 'password123',+ password_confirmation: 'password123',+ first_name: 'John',+ last_name: 'Doe',+})+```++## Guest Checkout++For guest checkout, use the `token` returned when creating a cart. The SDK automatically sends it via the `x-spree-token` header:++<AuthGuestCart />++```typescript+const options = { spreeToken: cart.token }++// Update cart with email+await client.carts.update(cart.id, {+ email: '[email protected]',+}, options)++// Complete checkout+await client.carts.complete(cart.id, options)+```diff --git a/docs/v5/developer/sdk/configuration.mdx b/docs/v5/developer/sdk/configuration.mdxnew file mode 100644index 0000000000..a78a7973aa--- /dev/null+++ b/docs/v5/developer/sdk/configuration.mdx@@ -0,0 +1,246 @@+---+title: Configuration+description: Configure the Spree JavaScript SDK — localization, currency headers, error handling, TypeScript types, and a custom fetch implementation.+canonical: "https://spreecommerce.org/docs/developer/sdk/configuration"+---++import LocalizationExample from '/snippets/store-api/localization-example.mdx'++## Localization & Currency++Pass locale and currency headers with any request. For full details, see the [Localization](/api-reference/store-api/localization) reference.++<LocalizationExample />++```typescript+// Works with all endpoints+const category = await client.categories.get('clothing/shirts', {+ expand: ['ancestors'],+}, {+ locale: 'de',+ currency: 'EUR',+})+```++import { Since } from '/snippets/since.mdx';++## Sales Channels <Since version="5.5" />++Select which [sales channel](/v5/developer/core-concepts/channels) scopes a request. The SDK sends the value as the `X-Spree-Channel` header. Pass either the channel `code` (e.g. `online`, `pos`, `wholesale`) or the prefixed ID (`ch_…`) — `code` is preferred since it's merchant-meaningful and stable across environments. When omitted, the store's default channel is used.++```typescript+// Client-level default — every request runs against the POS channel+const client = createClient({+ baseUrl: 'https://api.mystore.com',+ publishableKey: 'pk_xxx',+ channel: 'pos',+})++// Sticky setter — switch channels mid-session (e.g. after the user+// changes storefront context)+client.setChannel('wholesale')++// Per-request override — one request only+const products = await client.products.list({}, { channel: 'pos' })+```++The channel scopes product visibility (only products published on that channel are returned), pricing fallback (per-channel pricing rules), and order attribution (a cart created with `channel: 'pos'` gets `order.channel_id` set to the POS channel).++## Error Handling++```typescript+import { SpreeError } from '@spree/sdk';++try {+ await client.products.get('non-existent');+} catch (error) {+ if (error instanceof SpreeError) {+ console.log(error.code); // 'record_not_found'+ console.log(error.message); // 'Product not found'+ console.log(error.status); // 404+ console.log(error.details); // Validation errors (if any)+ }+}+```++## Custom Fetch++You can provide a custom fetch implementation:++```typescript+import { createClient } from '@spree/sdk';++const client = createClient({+ baseUrl: 'https://api.mystore.com',+ publishableKey: 'pk_xxx',+ fetch: customFetchImplementation,+});+```++## Monetary Amounts++All monetary values in the API are returned as **strings** (e.g., `"29.99"`, `"0.0"`), not numbers. This preserves decimal precision and avoids floating-point rounding issues.++```typescript+const order = await client.orders.get('or_abc123', {}, { token });++// Monetary fields are strings+order.total; // "129.99"+order.item_total; // "99.99"+order.delivery_total; // "10.00"+order.tax_total; // "20.00"++// Display fields include currency formatting+order.display_total; // "$129.99"++// Convert to number when needed for calculations+const total = parseFloat(order.total);+```++This applies to all monetary fields across all types: `Order`, `LineItem`, `Fulfillment`, `Payment`, `GiftCard`, `Price`, etc.++## TypeScript Support++The SDK includes full TypeScript support with generated types from the API serializers:++```typescript+import type {+ Product,+ Order,+ Cart,+ Variant,+ Category,+ LineItem,+ Address,+ Customer,+ PaginatedResponse,+} from '@spree/sdk';++// All responses are fully typed+const products: PaginatedResponse<Product> = await client.products.list();+const category: Category = await client.categories.get('clothing');+```++## Available Types++All types are exported as unprefixed names (e.g., `Product`, `Order`). Legacy `Store*` prefixed aliases (e.g., `StoreProduct`) are still available for backward compatibility.++### Core Types+- `Product` - Product data+- `Variant` - Variant data+- `Cart` - Cart data (uses `cart_` prefixed IDs)+- `Order` - Completed order data (uses `or_` prefixed IDs)+- `LineItem` - Line item in cart+- `Category` - Category+- `Country` - Country with states+- `State` - State/province+- `Address` - Customer address+- `Customer` - Customer profile+- `Market` - Market configuration (currency, locales, countries)++### Commerce Types+- `Payment` - Payment record+- `PaymentMethod` - Payment method+- `PaymentSession` - Provider-agnostic payment session+- `Fulfillment` - Fulfillment record+- `DeliveryRate` - Delivery rate option+- `DeliveryMethod` - Delivery method+- `CreditCard` - Saved credit card+- `GiftCard` - Gift card+- `Discount` - Discount applied to a cart or order++### Product Types+- `Media` - Product media (images, videos)+- `Price` - Price data+- `OptionType` - Option type (e.g., Size, Color)+- `OptionValue` - Option value (e.g., Small, Red)+- `DigitalLink` - Digital download link+- `Metafield` - Custom metafield data++### Wishlist Types+- `Wishlist` - Wishlist+- `WishlistItem` - Wishlist item++### Client Types+- `Client` - Main client interface+- `StoreClient` - Store API client class+- `ClientConfig` - Client configuration+- `RequestOptions` - Per-request options+- `RetryConfig` - Retry behavior configuration++### Utility Types+- `PaginatedResponse<T>` - Paginated API response+- `ListResponse<T>` - List API response+- `AuthTokens` - JWT tokens from login+- `AddressParams` - Address input parameters+- `UpdateCartParams` - Cart update parameters+- `CreatePaymentParams` - Direct payment creation parameters+- `CreatePaymentSessionParams` - Payment session creation parameters+- `UpdatePaymentSessionParams` - Payment session update parameters+- `CompletePaymentSessionParams` - Payment session completion parameters+- `ProductFiltersResponse` - Product filters response+- `CheckoutRequirement` - Checkout requirement (`{ step, field, message }`)++## Extending Types++All generated SDK types are TypeScript `interface`s, which means you can extend them via [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) when you customize API serializers on the backend.++### Example: Adding a Brand to Products++If you've customized the `ProductSerializer` in your app to include a `brand_id` attribute:++```ruby+# app/serializers/my_store/product_serializer.rb+module MyStore+ class ProductSerializer < Spree::Api::V3::ProductSerializer+ typelize brand_id: :string++ attribute :brand_id do |product|+ product.brand&.prefixed_id+ end+ end+end++# config/initializers/spree.rb+Spree.api.product_serializer = MyStore::ProductSerializer+```++You can extend the SDK type in your frontend code so TypeScript knows about the new field:++```typescript+// types/spree.d.ts+declare module '@spree/sdk' {+ interface Product {+ brand_id: string;+ }+}+```++Now `brand_id` is available on every `Product` across your app — no type casting needed:++```typescript+const products = await client.products.list();+products.data.forEach((product) => {+ console.log(product.brand_id); // fully typed+});+```++### Extending Zod Schemas++If you use the SDK's Zod schemas for runtime validation, extend them with `.extend()`:++```typescript+import { z } from 'zod';+import { ProductSchema } from '@spree/sdk/zod';++const MyProductSchema = ProductSchema.extend({+ brand_id: z.string(),+});++// Use for runtime validation+const product = MyProductSchema.parse(apiResponse);+```++<Note>+Declaration merging only affects TypeScript types (compile-time). Zod schemas perform runtime validation and must be extended separately if you need validation of custom fields.+</Note>diff --git a/docs/v5/developer/sdk/extending.mdx b/docs/v5/developer/sdk/extending.mdxnew file mode 100644index 0000000000..c84492b91a--- /dev/null+++ b/docs/v5/developer/sdk/extending.mdx@@ -0,0 +1,34 @@+---+title: Custom Endpoints+sidebarTitle: Custom Endpoints+description: Call your own custom Store API endpoints from the Spree TypeScript SDK using the built-in request method, with typed responses and shared auth handling.+canonical: "https://spreecommerce.org/docs/developer/sdk/extending"+---++The client exposes a `request` method — the same function that powers all built-in resources. Use it to call any Store API endpoint, including ones you've added yourself.++```typescript+import { createClient } from '@spree/sdk'+import type { PaginatedResponse } from '@spree/sdk'++const client = createClient({+ baseUrl: 'https://api.mystore.com',+ publishableKey: 'pk_YOUR_KEY',+})++interface Brand {+ id: string+ name: string+ slug: string | null+ description: string | null+ logo_url: string | null+}++// Paths are relative to /api/v3/store+const brands = await client.request<PaginatedResponse<Brand>>('GET', '/brands')+const nike = await client.request<Brand>('GET', '/brands/nike')+```++`client.request` uses the same auth headers, retry logic, and locale/currency defaults as `client.products.list()` or any other built-in resource.++For a complete walkthrough — creating the API endpoints on the backend, defining TypeScript types, filtering, and expanding associations — see the [API](/v5/developer/tutorial/api) and [SDK](/v5/developer/tutorial/sdk) tutorials.diff --git a/docs/v5/developer/sdk/quickstart.mdx b/docs/v5/developer/sdk/quickstart.mdxnew file mode 100644index 0000000000..a0b1037682--- /dev/null+++ b/docs/v5/developer/sdk/quickstart.mdx@@ -0,0 +1,90 @@+---+title: Spree TypeScript SDK quickstart for the Store API+sidebarTitle: Quickstart+description: Install @spree/sdk, configure the Store API client, and make your first calls to products, carts, checkout, and customer account endpoints from TypeScript.+canonical: "https://spreecommerce.org/docs/developer/sdk/quickstart"+---++`@spree/sdk` is the customer-facing SDK — products, carts, checkout, and account flows against the Store API. For back-office integrations (managing products, orders, customers, stock), use the [Admin SDK](/v5/developer/sdk/admin/quickstart).++## Installation++```bash+npm install @spree/sdk+# or+yarn add @spree/sdk+# or+pnpm add @spree/sdk+```++## Quick Start++```typescript+import { createClient } from '@spree/sdk';++// Initialize the client+const client = createClient({+ baseUrl: 'https://api.mystore.com',+ publishableKey: 'pk_xxx', // Store API+});++// Browse products (Store API)+const products = await client.products.list({+ limit: 10,+ expand: ['variants', 'media'],+});++// Get a single product+const product = await client.products.get('spree-tote');++// Authentication+const { token, user } = await client.auth.login({+ email: '[email protected]',+ password: 'password123',+});++// Create a cart and add items+const cart = await client.carts.create();+await client.carts.items.create(cart.id, {+ variant_id: 'var_abc123',+ quantity: 2,+}, { spreeToken: cart.token });++// Checkout flow+await client.carts.complete(cart.id, { spreeToken: cart.token });+```++## Nested Resources++The SDK uses a resource builder pattern for nested resources:++| Parent Resource | Nested Resource | Available Methods |+|-----------------|-----------------|-------------------|+| `carts` | `items` | `create`, `update`, `delete` |+| `carts` | `payments` | `list`, `get`, `create` |+| `carts` | `paymentMethods` | `list` |+| `carts` | `paymentSessions` | `create`, `get`, `update`, `complete` |+| `carts` | `fulfillments` | `list`, `update` |+| `carts` | `discountCodes` | `apply`, `remove` |+| `carts` | `giftCards` | `apply`, `remove` |+| `carts` | `storeCredits` | `apply`, `remove` |+| `customer` | `addresses` | `list`, `get`, `create`, `update`, `delete`, `markAsDefault` |+| `customer` | `creditCards` | `list`, `get`, `delete` |+| `customer` | `giftCards` | `list`, `get` |+| `customer` | `orders` | `list` |+| `customer` | `paymentSetupSessions` | `create`, `get`, `complete` |+| `policies` | — | `list`, `get` |+| `wishlists` | `items` | `create`, `update`, `delete` |++```typescript+// Nested resources follow the pattern: client.parent.nested.method(parentId, ...)+await client.carts.items.create(cartId, params, options);+await client.carts.payments.list(cartId, options);+await client.carts.fulfillments.update(cartId, fulfillmentId, params, options);+await client.customer.addresses.list({}, options);+await client.wishlists.items.create(wishlistId, params, options);+```++## Pair with AI agents++Building your storefront with an AI coding agent? The [Spree agent skills](/v5/developer/agentic/agent-skills) include dedicated SDK and storefront skills (typed clients, Ransack filtering, error handling, custom endpoints), and the [docs MCP server](/v5/developer/agentic/mcp) gives your agent the full SDK reference on demand. See [Agentic Development](/v5/developer/agentic/overview).diff --git a/docs/v5/developer/sdk/store/account.mdx b/docs/v5/developer/sdk/store/account.mdxnew file mode 100644index 0000000000..89cef5c309--- /dev/null+++ b/docs/v5/developer/sdk/store/account.mdx@@ -0,0 +1,83 @@+---+title: Customer Account+description: Manage customer profiles, addresses, and credit cards with the Spree SDK+canonical: "https://spreecommerce.org/docs/developer/sdk/store/account"+---++## Customer Profile++```typescript+const options = { token: jwtToken };++// Get profile+const profile = await client.customer.get(options);+// profile includes `available_store_credit_total` and `display_available_store_credit_total`++// Update profile+await client.customer.update({+ first_name: 'John',+ last_name: 'Doe',+}, options);+```++## Addresses++```typescript+const options = { token: jwtToken };++// List addresses+const { data: addresses } = await client.customer.addresses.list({}, options);++// Get address by ID+const address = await client.customer.addresses.get('addr_xxx', options);++// Create address+await client.customer.addresses.create({+ first_name: 'John',+ last_name: 'Doe',+ address1: '123 Main St',+ city: 'New York',+ postal_code: '10001',+ country_iso: 'US',+ state_abbr: 'NY',+ is_default_billing: true, // Optional — set as default billing address+ is_default_shipping: true, // Optional — set as default shipping address+}, options);++// Update address+await client.customer.addresses.update('addr_xxx', {+ city: 'Brooklyn',+ is_default_billing: true, // Optional — set as default billing address+ is_default_shipping: false, // Optional — set as default shipping address+}, options);++// Delete address+await client.customer.addresses.delete('addr_xxx', options);+```++## Store Credits++```typescript+const options = { token: jwtToken };++// List store credits+const { data: credits } = await client.customer.storeCredits.list({}, options);++// Get a specific store credit+const credit = await client.customer.storeCredits.get('sc_xxx', options);+```++## Credit Cards++```typescript+const options = { token: jwtToken };++// List saved credit cards+const { data: cards } = await client.customer.creditCards.list({}, options);++// Get credit card by ID+const card = await client.customer.creditCards.get('cc_xxx', options);++// Delete credit card+await client.customer.creditCards.delete('cc_xxx', options);+```diff --git a/docs/v5/developer/sdk/store/cart-checkout.mdx b/docs/v5/developer/sdk/store/cart-checkout.mdxnew file mode 100644index 0000000000..cddae8b888--- /dev/null+++ b/docs/v5/developer/sdk/store/cart-checkout.mdx@@ -0,0 +1,161 @@+---+title: Cart, Checkout & Orders+description: Manage carts, line items, coupons, checkout flow, and completed orders with the Spree SDK+canonical: "https://spreecommerce.org/docs/developer/sdk/store/cart-checkout"+---++The Store API is split into two resource groups:++- **Carts** — managing shopping carts, items, coupon codes, checkout flow (addresses, delivery, payments, completion)+- **Orders** — retrieving completed orders++All cart and checkout endpoints require a `cartId` as the first argument.++## Carts++### Create & Retrieve++```typescript+// Create a new cart+const cart = await client.carts.create();++// Get a specific cart+const cart = await client.carts.get(cartId, { spreeToken: 'xxx' });++// List carts+const carts = await client.carts.list();++// Delete a cart+await client.carts.delete(cartId, { spreeToken: cart.token });++// Associate guest cart with authenticated user+// (after user logs in, merge their guest cart with their account)+await client.carts.associate(cartId, {+ token: jwtToken, // User's JWT token+ spreeToken: cart.token, // Guest cart token+});+```++### Items++```typescript+const options = { spreeToken: cart.token };++// Add item+await client.carts.items.create(cartId, {+ variant_id: 'var_123',+ quantity: 2,+}, options);++// Update item quantity+await client.carts.items.update(cartId, lineItemId, {+ quantity: 3,+}, options);++// Remove item+await client.carts.items.delete(cartId, lineItemId, options);+```++### Discount Codes++```typescript+const options = { spreeToken: cart.token };++// Apply a discount code+await client.carts.discountCodes.apply(cartId, 'SAVE20', options);++// Remove a discount code+await client.carts.discountCodes.remove(cartId, 'SAVE20', options);+```++### Gift Cards++```typescript+// Apply a gift card (reduces amount_due, not total)+const cart = await client.carts.giftCards.apply(cartId, 'GC-ABCD-1234', options);++// Remove a gift card (ID from cart.gift_card.id)+await client.carts.giftCards.remove(cartId, 'gc_abc123', options);+```++## Checkout++### Update Cart++```typescript+await client.carts.update(cartId, {+ email: '[email protected]',+ shipping_address: {+ first_name: 'John',+ last_name: 'Doe',+ address1: '123 Main St',+ city: 'New York',+ postal_code: '10001',+ phone: '+1 555 123 4567',+ country_iso: 'US',+ state_abbr: 'NY',+ },+ billing_address_id: 'addr_xxx', // Or use existing address by ID+}, { spreeToken: cart.token });+```++### Complete Checkout++```typescript+await client.carts.complete(cartId, { spreeToken: cart.token });+```++### Fulfillments++Fulfillments are included in the cart response — there is no separate list endpoint.++```typescript+const options = { spreeToken: cart.token };++// Access fulfillments from the cart response+const cart = await client.carts.get(cartId, options);+const fulfillments = cart.fulfillments;++// Select a delivery rate+await client.carts.fulfillments.update(cartId, fulfillmentId, {+ selected_delivery_rate_id: 'rate_xxx',+}, options);+```++### Store Credits++```typescript+const options = { spreeToken: cart.token };++// Apply store credit (applies maximum available by default)+await client.carts.storeCredits.apply(cartId, undefined, options);++// Apply specific amount of store credit+await client.carts.storeCredits.apply(cartId, 25.00, options);++// Remove store credit from order+await client.carts.storeCredits.remove(cartId, options);+```++The cart/order response includes store credit and gift card totals:++- `store_credit_total` / `display_store_credit_total` — total store credit applied+- `gift_card_total` / `display_gift_card_total` — total gift card value applied+- `covered_by_store_credit` — boolean, whether the order is fully covered by store credit+- `gift_card` — associated gift card (if applicable)++## Orders++### Get a Completed Order++```typescript+const order = await client.orders.get('R123456789', {+ expand: ['items', 'fulfillments'],+}, { spreeToken: cart.token });+```++### List Orders (Authenticated Customer)++```typescript+const orders = await client.customer.orders.list({}, { token });+```diff --git a/docs/v5/developer/sdk/store/markets.mdx b/docs/v5/developer/sdk/store/markets.mdxnew file mode 100644index 0000000000..24dabeba22--- /dev/null+++ b/docs/v5/developer/sdk/store/markets.mdx@@ -0,0 +1,164 @@+---+title: Markets+description: Use the Spree Storefront SDK to list markets, resolve a market by country, and fetch the countries available within each market for checkout.+canonical: "https://spreecommerce.org/docs/developer/sdk/store/markets"+---++## List Markets++Returns all markets for the current store with their countries, currency, locales, and tax configuration.++<CodeGroup>++```typescript SDK+const { data: markets } = await client.markets.list()++markets.forEach(market => {+ market.id // "mkt_UkLWZg9DAJ"+ market.name // "North America"+ market.currency // "USD"+ market.default_locale // "en"+ market.tax_inclusive // false+ market.default // true+ market.supported_locales // ["en", "es"]+ market.countries // [{ iso: "US", name: "United States of America", ... }]+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/markets' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++**Response:**++```json+{+ "data": [+ {+ "id": "mkt_UkLWZg9DAJ",+ "name": "North America",+ "currency": "USD",+ "default_locale": "en",+ "tax_inclusive": false,+ "default": true,+ "supported_locales": ["en", "es"],+ "countries": [+ { "iso": "US", "iso3": "USA", "name": "United States of America", "states_required": true, "zipcode_required": true }+ ]+ },+ {+ "id": "mkt_gbHJdmfrXB",+ "name": "Europe",+ "currency": "EUR",+ "default_locale": "de",+ "tax_inclusive": true,+ "default": false,+ "supported_locales": ["de", "en", "fr"],+ "countries": [+ { "iso": "DE", "iso3": "DEU", "name": "Germany", "states_required": false, "zipcode_required": true },+ { "iso": "FR", "iso3": "FRA", "name": "France", "states_required": false, "zipcode_required": true }+ ]+ }+ ]+}+```++## Get a Market++<CodeGroup>++```typescript SDK+const market = await client.markets.get('mkt_gbHJdmfrXB')++market.name // "Europe"+market.currency // "EUR"+market.countries // [{ iso: "DE", ... }, { iso: "FR", ... }]+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/markets/mkt_gbHJdmfrXB' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++## Resolve Market by Country++Determine which market applies for a given country ISO code. Useful for auto-selecting the correct currency and locale when a customer's location is known.++<CodeGroup>++```typescript SDK+const market = await client.markets.resolve('DE')++market.id // "mkt_gbHJdmfrXB"+market.name // "Europe"+market.currency // "EUR"+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/markets/resolve?country=DE' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++<Info>+If no market matches the given country, a `404` error is returned.+</Info>++## List Countries in a Market++Returns countries belonging to a specific market. Use this for address form country dropdowns during checkout.++<CodeGroup>++```typescript SDK+const { data: countries } = await client.markets.countries.list('mkt_gbHJdmfrXB')++countries.forEach(country => {+ country.iso // "DE"+ country.name // "Germany"+ country.states_required // false+ country.zipcode_required // true+})+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/markets/mkt_gbHJdmfrXB/countries' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++## Get a Country in a Market++Returns a single country by ISO code within a market. Use `expand: ['states']` for address forms that need state/province dropdowns.++<CodeGroup>++```typescript SDK+const country = await client.markets.countries.get('mkt_gbHJdmfrXB', 'US', {+ expand: ['states'],+})++country.iso // "US"+country.name // "United States of America"+country.states // [{ id: "st_xxx", name: "New York", abbr: "NY" }, ...]+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/markets/mkt_gbHJdmfrXB/countries/US?expand=states' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++## Related Documentation++- [Markets](/v5/developer/core-concepts/markets) — Market concepts, zones, and configuration+- [Localization](/api-reference/store-api/localization) — Locale and currency headers+- [Geography](/v5/developer/sdk/store/products#geography) — Global country endpointsdiff --git a/docs/v5/developer/sdk/store/payments.mdx b/docs/v5/developer/sdk/store/payments.mdxnew file mode 100644index 0000000000..e96a8969e2--- /dev/null+++ b/docs/v5/developer/sdk/store/payments.mdx@@ -0,0 +1,99 @@+---+title: Payments & Delivery+description: Handle payments, payment sessions, and delivery with the Spree SDK+canonical: "https://spreecommerce.org/docs/developer/sdk/store/payments"+---++All payment and delivery endpoints require a `cartId` as the first argument.++## Payment Methods++Payment methods, payments, and fulfillments are included in the cart response -- there are no separate list or get endpoints for these resources.++```typescript+const options = { spreeToken: cart.token };++// Access payment methods, payments, and fulfillments from the cart response+const cart = await client.carts.get(cartId, options);+const paymentMethods = cart.payment_methods;+const payments = cart.payments;+const fulfillments = cart.fulfillments;++// Each payment method includes a `session_required` flag:+// - true → use Payment Sessions (Stripe, Adyen, PayPal, etc.)+// - false → use direct payment creation (Check, Cash on Delivery, Bank Transfer, etc.)+```++## Payments++```typescript+const options = { spreeToken: cart.token };++// Create a payment for a non-session payment method+// (e.g. Check, Cash on Delivery, Bank Transfer, Purchase Order)+const payment = await client.carts.payments.create(cartId, {+ payment_method_id: 'pm_xxx',+ amount: '99.99', // Optional, defaults to order total minus store credits+ metadata: { // Optional, write-only metadata+ purchase_order_number: 'PO-12345',+ },+}, options);+```++<Note>+ `payments.create()` only works with non-session payment methods (where `session_required` is `false`).+ For session-based gateways like Stripe or Adyen, use `paymentSessions.create()` instead.+</Note>++## Payment Sessions++Payment sessions provide a unified, provider-agnostic interface for payment processing. They work with any payment gateway (Stripe, Adyen, PayPal, etc.) through a single API.++```typescript+const options = { spreeToken: cart.token };++// Create a payment session (initializes a session with the payment gateway)+const session = await client.carts.paymentSessions.create(cartId, {+ payment_method_id: 'pm_xxx',+ amount: '99.99', // Optional, defaults to order total+ external_data: { // Optional, provider-specific data+ return_url: 'https://mystore.com/checkout/complete',+ },+}, options);++// The session contains provider-specific data (e.g., Stripe client_secret)+console.log(session.external_data.client_secret);++// Get a payment session+const existing = await client.carts.paymentSessions.get(+ cartId, session.id, options+);++// Update a payment session (e.g., after order total changes)+await client.carts.paymentSessions.update(cartId, session.id, {+ amount: '149.99',+}, options);++// Complete the payment session (after customer confirms payment on the frontend)+const completed = await client.carts.paymentSessions.complete(+ cartId, session.id,+ { session_result: 'success' },+ options+);+console.log(completed.status); // 'completed'+```++## Fulfillments++```typescript+const options = { spreeToken: cart.token };++// Fulfillments are included in the cart response+const cart = await client.carts.get(cartId, options);+const fulfillments = cart.fulfillments;++// Select a delivery rate+await client.carts.fulfillments.update(cartId, fulfillmentId, {+ selected_delivery_rate_id: 'rate_xxx',+}, options);+```diff --git a/docs/v5/developer/sdk/store/products.mdx b/docs/v5/developer/sdk/store/products.mdxnew file mode 100644index 0000000000..477e5f07fe--- /dev/null+++ b/docs/v5/developer/sdk/store/products.mdx@@ -0,0 +1,171 @@+---+title: Products & Categories+description: Browse products and categories with the Spree SDK+canonical: "https://spreecommerce.org/docs/developer/sdk/store/products"+---++## Products++### List Products++```typescript+const products = await client.products.list({+ page: 1,+ limit: 25,+ expand: ['variants', 'media', 'categories'],+});+```++### Filtering Products++Use flat param keys — the SDK wraps them in `q[...]` automatically:++```typescript+const products = await client.products.list({+ name_cont: 'shirt', // Name contains+ price_gte: 20, // Min price+ price_lte: 100, // Max price+ with_option_value_ids: ['optval_abc', 'optval_def'], // By option values+ in_stock: true, // In stock only+ search: 'blue shirt', // Full-text search+});+```++### Sorting Products++Pass `sort` with one of the supported values. Prefix with `-` for descending order:++```typescript+const products = await client.products.list({+ sort: 'price', // price, -price, best_selling,+ // name, -name, -available_on, available_on+});+```++### Field Selection++Request only specific fields to reduce payload size:++```typescript+const products = await client.products.list({+ fields: ['name', 'slug', 'price', 'display_price'],+});++const product = await client.products.get('spree-tote', {+ fields: ['name', 'slug', 'price'],+ expand: ['media'], // expanded associations are always included+});+```++`id` is always included. Omit `fields` to return all fields.++### Nested Expand++Use dot notation to expand nested associations (up to 4 levels):++```typescript+// Expand variants with their images in one request+const product = await client.products.get('spree-tote', {+ expand: ['variants.media', 'option_types'],+});++// Access nested data+product.variants.forEach(variant => {+ console.log(variant.media); // Media are included+});+```++### Get a Product++Fetch a single product by slug or prefix ID:++```typescript+const product = await client.products.get('spree-tote', {+ expand: ['variants', 'media'],+});+```++### Prior Price (EU Omnibus Directive)++When a product is on sale, EU regulations require displaying the lowest price in the last 30 days. Use the `prior_price` expand to fetch this:++```typescript+const product = await client.products.get('spree-tote', {+ expand: ['prior_price'],+});++if (product.prior_price) {+ console.log(product.prior_price.amount); // "9.99"+ console.log(product.prior_price.display_amount); // "$9.99"+ console.log(product.prior_price.currency); // "USD"+ console.log(product.prior_price.recorded_at); // "2026-03-10T..."+}+```++<Info>+Prior price is only relevant on product detail pages (PDP), not on listings. It returns `null` if no price history exists within the 30-day window. Price history tracking can be disabled globally via `Spree::Config[:track_price_history] = false`.+</Info>++### Product Filters++Get available filters (price range, availability, options, categories) and sort options for building filter UIs:++```typescript+const filters = await client.products.filters({+ category_id: 'ctg_abc123', // Optional: scope filters to a category+});++// Response:+// {+// filters: [+// { id: 'price', type: 'price_range', min: 9.99, max: 199.99, currency: 'USD' },+// { id: 'availability', type: 'availability', options: [{ id: 'in_stock', count: 42 }, ...] },+// { id: 'opttype_abc', type: 'option', name: 'color', presentation: 'Color', options: [...] },+// { id: 'categories', type: 'category', options: [{ id: 'ctg_abc', name: 'Shirts', permalink: '...', count: 12 }] },+// ],+// sort_options: [{ id: 'manual' }, { id: 'price' }, { id: 'best_selling' }, ...],+// default_sort: 'manual',+// total_count: 85,+// }+```++## Categories++### List Categories++```typescript+const categories = await client.categories.list({+ depth_eq: 1, // Top-level categories only+});+```++### Get a Category++Fetch by ID or permalink:++```typescript+const category = await client.categories.get('clothing/shirts', {+ expand: ['ancestors', 'children'], // For breadcrumbs and subcategories+});+```++### List Products in a Category++```typescript+const categoryProducts = await client.categories.products.list('clothing/shirts', {+ page: 1,+ limit: 12,+ expand: ['media', 'default_variant'],+});+```++## Geography++```typescript+// List countries available for checkout+const { data: countries } = await client.countries.list();++// Get country by ISO code (includes states)+const usa = await client.countries.get('US');+console.log(usa.states); // Array of states+```diff --git a/docs/v5/developer/sdk/store/wishlists.mdx b/docs/v5/developer/sdk/store/wishlists.mdxnew file mode 100644index 0000000000..e935fd1a50--- /dev/null+++ b/docs/v5/developer/sdk/store/wishlists.mdx@@ -0,0 +1,53 @@+---+title: Wishlists+description: Manage wishlists and wished items with the Spree SDK+canonical: "https://spreecommerce.org/docs/developer/sdk/store/wishlists"+---++## Wishlists++```typescript+const options = { token: jwtToken };++// List wishlists+const { data: wishlists } = await client.wishlists.list({}, options);++// Get wishlist by ID+const wishlist = await client.wishlists.get('wl_xxx', {+ expand: ['wished_items'],+}, options);++// Create wishlist+const newWishlist = await client.wishlists.create({+ name: 'Birthday Ideas',+ is_private: true,+}, options);++// Update wishlist+await client.wishlists.update('wl_xxx', {+ name: 'Updated Name',+}, options);++// Delete wishlist+await client.wishlists.delete('wl_xxx', options);+```++## Wishlist Items++```typescript+const options = { token: jwtToken };++// Add item to wishlist+await client.wishlists.items.create('wl_xxx', {+ variant_id: 'var_123',+ quantity: 1,+}, options);++// Update item quantity+await client.wishlists.items.update('wl_xxx', 'wi_xxx', {+ quantity: 2,+}, options);++// Remove item from wishlist+await client.wishlists.items.delete('wl_xxx', 'wi_xxx', options);+```diff --git a/docs/v5/developer/security/pci_compliance.mdx b/docs/v5/developer/security/pci_compliance.mdxnew file mode 100644index 0000000000..78cc97f62f--- /dev/null+++ b/docs/v5/developer/security/pci_compliance.mdx@@ -0,0 +1,16 @@+---+title: "PCI Compliance"+canonical: "https://spreecommerce.org/docs/developer/security/pci_compliance"+---++All store owners wishing to process credit card transactions should be familiar with [PCI Compliance](http://en.wikipedia.org/wiki/Pci_compliance). All officially supported payment gateways — [Spree Stripe](https://github.com/spree/spree_stripe), [Spree Adyen](https://github.com/spree/spree_adyen), and [Spree PayPal Checkout](https://github.com/spree/spree_paypal_checkout) — are fully PCI-compliant.++## Using payment tokens++We do not transmit or store Credit Card numbers. Instead we're using payment processor tokens supplied by their SDKs to authorize and charge customer cards. Sensitive payment data is collected directly by the gateway's frontend SDK (e.g., Stripe.js, Adyen Drop-in) and never touches your server.++## 3-D Secure and Strong Customer Authentication support++[Spree Stripe integration](https://github.com/spree/spree_stripe) supports [Strong Customer Authentication (SCA)](https://stripe.com/en-pl/guides/strong-customer-authentication) out of the box. We also use Stripe JavaScript SDK to render all payment forms.++[Spree Adyen integration](https://github.com/spree/spree_adyen) supports 3D Secure 2.0 through the Adyen Drop-in component.diff --git a/docs/v5/developer/security/security_policy.mdx b/docs/v5/developer/security/security_policy.mdxnew file mode 100644index 0000000000..a45332f682--- /dev/null+++ b/docs/v5/developer/security/security_policy.mdx@@ -0,0 +1,69 @@+---+title: "Security Policy"+description: "How to report vulnerabilities, supported versions, and Spree's security practices."+canonical: "https://spreecommerce.org/docs/developer/security/security_policy"+---++## Overview++Proper application design, intelligent programming, and secure infrastructure are all essential in creating a secure e-commerce store using any software (Spree included). The Spree team has done its best to provide you with the tools to create a secure and profitable web presence, but it is up to you to take these tools and put them in good practice. We highly recommend reading and understanding the [Rails Security Guide](https://guides.rubyonrails.org/security.html).++## Supported Versions++The following versions are actively maintained and receive security patches.++| Version | Release date | End of life |+| ------- | ------------ | ----------- |+| 5.0 | 26.03.2025 | 26.03.2028 |+| 4.10 | 06.09.2024 | 06.09.2027 |++If you're using an older version [please upgrade](../upgrades/). Have trouble upgrading? [Contact us for support](https://spreecommerce.org/contact/).++**Versions that are not listed above will not receive any security patches or fixes.**++## Reporting Security Issues++**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.**++Instead, please send an email to [[email protected]](mailto:[email protected]).++Please include as much of the following information as possible to help us triage your report:++- Type of vulnerability (e.g. SQL injection, XSS, CSRF, etc.)+- Affected version(s)+- Step-by-step instructions to reproduce the issue+- Proof of concept or exploit code (if available)+- Impact assessment of the vulnerability++### Submitting a Patch++If you would like to provide a patch yourself for the security issue **do not open a pull request for it**. Instead, create a commit on your fork of Spree and run this command:++```bash+git format-patch HEAD~1..HEAD --stdout > patch.txt+```++Email a description of the patch along with the `patch.txt` file to [[email protected]](mailto:[email protected]).++### Disclosure Process++1. Security report is received and acknowledged within **48 hours**.+2. The issue is confirmed and a severity level is assigned.+3. A fix is developed and tested against all supported versions.+4. A new release is published with the fix and a [GitHub Security Advisory](https://github.com/spree/spree/security/advisories) is created.+5. Reporter is credited in the advisory (unless anonymity is requested).++### Security Advisories++Published security advisories can be found at [GitHub Security Advisories](https://github.com/spree/spree/security/advisories).++## Security Best Practices++Spree API is built on **Ruby on Rails** which provides strong security defaults including protection against SQL injection, CSRF, and XSS. For more details on how Spree handles security in production environments, see the [Enterprise Security Overview](/v5/user/security).++We recommend:++- Keeping Spree and all dependencies up to date+- Following the [Rails Security Guide](https://guides.rubyonrails.org/security.html)+- Using [bundler-audit](https://github.com/rubysec/bundler-audit) to scan for known vulnerabilities in dependencies+- Running [brakeman](https://github.com/presidentbeef/brakeman) for static security analysisdiff --git a/docs/v5/developer/storefront/nextjs/architecture.mdx b/docs/v5/developer/storefront/nextjs/architecture.mdxnew file mode 100644index 0000000000..ff799c13ee--- /dev/null+++ b/docs/v5/developer/storefront/nextjs/architecture.mdx@@ -0,0 +1,162 @@+---+title: Architecture+description: Server-first architecture, project structure, and auth flow+canonical: "https://spreecommerce.org/docs/developer/storefront/nextjs/architecture"+---++## Server-First Pattern++The storefront follows a **server-first architecture** where all API calls are made server-side. The Spree API key is never exposed to the browser.++```+Browser → Server Action → @spree/sdk → Spree API+ (with httpOnly cookies via src/lib/spree helpers)+```++- **Server Actions** (`src/lib/data/`) — call `@spree/sdk` directly with auth/cookie helpers from `src/lib/spree`+- **httpOnly Cookies** — auth tokens, cart tokens, and locale are stored securely+- **No Client-Side API Calls** — the Spree API key stays on the server+- **Auto-Localization** — locale and country are read from cookies via `getLocaleOptions()`++## Project Structure++```+src/+├── app/+│ └── [country]/[locale]/ # Localized routes+│ ├── (storefront)/ # Main storefront layout+│ │ ├── page.tsx # Homepage+│ │ ├── account/ # Customer account+│ │ │ ├── addresses/ # Address management+│ │ │ ├── credit-cards/ # Saved payment methods+│ │ │ ├── gift-cards/ # Gift cards+│ │ │ ├── orders/ # Order history+│ │ │ │ └── [id]/ # Order details+│ │ │ ├── profile/ # Profile settings+│ │ │ └── register/ # Registration+│ │ ├── cart/ # Shopping cart+│ │ ├── products/ # Product listing+│ │ │ └── [slug]/ # Product details+│ │ ├── t/[...permalink]/ # Category pages+│ │ └── categories/ # Category overview+│ ├── (checkout)/ # Checkout layout (no header/footer)+│ │ ├── checkout/[id]/ # Checkout flow+│ │ └── order-placed/[id]/ # Order confirmation+│ └── (wholesale)/ # Opt-in B2B portal (gated — see Wholesale guide)+│ └── wholesale/+│ ├── page.tsx # Trade catalog+│ ├── products/[slug]/ # Wholesale PDP+│ ├── cart/ # Wholesale cart+│ ├── quick-order/ # SKU quick-order form+│ ├── apply/ # Trade-account application+│ └── _components/ # Gate, header, sign-in wall, pending, guest browse+├── components/+│ ├── cart/ # CartDrawer+│ ├── checkout/ # AddressStep, DeliveryStep, PaymentStep, etc.+│ ├── layout/ # Header, Footer, CountrySwitcher+│ ├── navigation/ # Breadcrumbs+│ ├── products/ # ProductCard, ProductGrid, Filters, MediaGallery, HiddenPricePrompt+│ └── search/ # SearchBar+├── contexts/+│ ├── AuthContext.tsx # Auth state+│ ├── CartContext.tsx # Client-side cart state sync+│ ├── CheckoutContext.tsx # Checkout flow state+│ ├── HiddenPricingContext.tsx # Prices-hidden signal for wholesale guests+│ └── StoreContext.tsx # Store/locale/currency state+├── hooks/+│ ├── useCarouselProducts.ts # Product carousel data+│ └── useProductListing.ts # Product listing with filters+└── lib/+ ├── analytics/ # GTM integration+ ├── constants.ts # App constants+ ├── data/ # Server Actions (call @spree/sdk directly)+ │ ├── addresses.ts # Address CRUD+ │ ├── cart.ts # Cart operations+ │ ├── checkout.ts # Checkout flow+ │ ├── cookies.ts # Auth check helper+ │ ├── countries.ts # Countries/regions+ │ ├── credit-cards.ts # Payment methods+ │ ├── customer.ts # Auth & profile+ │ ├── gift-cards.ts # Gift cards+ │ ├── orders.ts # Order history+ │ ├── payment.ts # Payment processing+ │ ├── products.ts # Product queries+ │ ├── categories.ts # Categories+ │ ├── wholesale.ts # Wholesale channel + catalog + quick-order+ │ ├── utils.ts # Shared helpers (actionResult, withFallback)+ │ └── … # One file per domain — see src/lib/data/+ ├── spree/ # Spree integration (client, cookies, auth refresh, middleware, surface)+ ├── wholesale.ts # Approval check + volume-pricing helpers+ └── utils/ # Client utilities+ ├── address.ts # Address formatting+ ├── cookies.ts # Cookie helpers+ ├── credit-card.ts # Card formatting+ ├── path.ts # URL path helpers+ └── product-query.ts # Product filter query builder+```++The `(wholesale)` route group is an opt-in B2B portal, off unless a wholesale channel is configured. Its gating, surfaces, and pricing modes are covered in the [Wholesale Portal](/v5/developer/storefront/nextjs/wholesale) guide.++## Authentication Flow++1. User submits login form+2. Server action calls `@spree/sdk` to authenticate+3. JWT token is stored in an httpOnly cookie via `src/lib/spree` cookie helpers+4. Subsequent requests use `withAuthRefresh()` which reads the token from cookies automatically+5. Token is never accessible to client-side JavaScript++```typescript+// src/lib/data/customer.ts+import { getClient, withAuthRefresh, setAccessToken, setRefreshToken } from '@/lib/spree'++export async function login(email: string, password: string) {+ const result = await getClient().auth.login({ email, password })+ await setAccessToken(result.token)+ await setRefreshToken(result.refresh_token)+ return { success: true, user: result.user }+}++export async function getCustomer() {+ return withAuthRefresh(async (options) => {+ return getClient().customer.get(options) // reads token from cookie+ })+}+```++## Multi-Region++The storefront serves multiple countries, currencies, and languages from one deployment via `/{country}/{locale}` URL segments and an edge middleware that detects and persists the visitor's region. See the [Multi-Region](/v5/developer/storefront/nextjs/multi-region) guide.++## Server Actions++All data fetching is done through server actions in `src/lib/data/`. These call `@spree/sdk` directly, using `src/lib/spree` helpers for auth and locale:++```typescript+// Products — use getLocaleOptions() for locale-aware reads+import { getProducts, getProduct, getProductFilters } from '@/lib/data/products'++const products = await getProducts({ limit: 12 })+const product = await getProduct('product-slug')+const filters = await getProductFilters()++// Cart — use getCartOptions()/requireCartId() for cart operations+import { getCart, addToCart, updateCartItem, removeCartItem } from '@/lib/data/cart'++const cart = await getCart()+await addToCart('var_xxx', 1)+await updateCartItem('li_xxx', 2)+await removeCartItem('li_xxx')++// Authentication — use withAuthRefresh() for authenticated endpoints+import { login, register, logout, getCustomer } from '@/lib/data/customer'++await login('[email protected]', 'password')+const customer = await getCustomer()+await logout()++// Addresses — use withAuthRefresh() for customer data+import { getAddresses, createAddress, updateAddress, deleteAddress } from '@/lib/data/addresses'++const addresses = await getAddresses()+await createAddress({ first_name: 'John', ... })+```diff --git a/docs/v5/developer/storefront/nextjs/customization.mdx b/docs/v5/developer/storefront/nextjs/customization.mdxnew file mode 100644index 0000000000..264df3b04b--- /dev/null+++ b/docs/v5/developer/storefront/nextjs/customization.mdx@@ -0,0 +1,130 @@+---+title: Customization+description: Customize and extend the Spree Next.js Storefront+canonical: "https://spreecommerce.org/docs/developer/storefront/nextjs/customization"+---++The storefront is yours to modify — the code ships in your project so you can restyle it, swap components, and change the data layer directly. Scaffold a project with [`create-spree-app`](/v5/developer/storefront/nextjs/quickstart#installation), then edit the storefront under `apps/storefront/`.++## Tracking Upstream Updates++The storefront evolves upstream. To keep pulling improvements while you customize, own the code in your own Git repository (a fork of [spree/storefront](https://github.com/spree/storefront), or your own repo with the storefront as an upstream remote):++```bash+# Point an "upstream" remote at the official storefront+git remote add upstream https://github.com/spree/storefront.git++# Pull in the latest changes+git fetch upstream+git merge upstream/main+```++Resolve any conflicts in your customized files, then commit.++## Styling++The storefront uses Tailwind CSS 4, which replaces the traditional `tailwind.config.ts` with CSS-native configuration via the `@theme` directive in `src/app/globals.css`.++### Theme Customization++Edit the `@theme inline` block in `src/app/globals.css` to change colors, fonts, and other design tokens:++```css+@import "tailwindcss";++:root {+ --background: #fcfaf7;+ --foreground: #171717;+}++@theme inline {+ --color-background: var(--background);+ --color-foreground: var(--foreground);+ --font-sans: var(--font-geist);++ /* Replace with your brand colors */+ --color-primary-50: #eff6ff;+ --color-primary-100: #dbeafe;+ --color-primary-200: #bfdbfe;+ --color-primary-300: #93c5fd;+ --color-primary-400: #60a5fa;+ --color-primary-500: #0077ff;+ --color-primary-600: #0066dd;+ --color-primary-700: #0055bb;+ --color-primary-800: #004499;+ --color-primary-900: #003377;+ --color-primary-950: #001d4d;+}+```++Variables defined in `@theme inline` become Tailwind utilities automatically — for example, `--color-primary-500` maps to `bg-primary-500`, `text-primary-500`, etc.++## Components++All components live in `src/components/` and can be customized or replaced:++```+src/components/+├── cart/ # CartDrawer+├── checkout/ # AddressStep, DeliveryStep, PaymentStep, StripePaymentForm, etc.+├── layout/ # Header, Footer, CountrySwitcher+├── navigation/ # Breadcrumbs+├── products/ # ProductCard, ProductGrid, ProductCarousel, Filters, MediaGallery, VariantPicker+└── search/ # SearchBar+```++Components use standard React patterns — modify them directly or replace them entirely with your own implementations.++## Data Layer++To customize API behavior, modify the server actions in `src/lib/data/`. Each file handles a specific domain:++| File | Purpose |+|------|---------|+| `products.ts` | Product listing and detail queries |+| `cart.ts` | Cart operations (add, update, remove) |+| `checkout.ts` | Checkout flow (addresses, shipping, completion) |+| `customer.ts` | Authentication and profile management |+| `addresses.ts` | Address CRUD |+| `orders.ts` | Order history |+| `payment.ts` | Payment sessions and processing |+| `categories.ts` | Categories |+| `countries.ts` | Country and region data |+| `cookies.ts` | Auth check helper |+| `store.ts` | Store configuration |+| `credit-cards.ts` | Saved payment methods |+| `gift-cards.ts` | Gift card management |+| `utils.ts` | Shared helpers (error handling, fallbacks) |++These server actions call `@spree/sdk` directly, using helpers in `src/lib/spree/` for auth cookies and locale resolution. You can add custom logic, caching strategies, or additional transformations as needed.++## Adding New Pages++Follow the existing App Router pattern with localized routes. Place pages under the `(storefront)` route group to inherit the shared header/footer layout:++```+src/app/[country]/[locale]/(storefront)/your-new-page/page.tsx+```++```typescript+import { getProducts } from '@/lib/data/products';++export default async function YourNewPage() {+ const products = await getProducts({ limit: 6 });++ return (+ <div>+ <h1>Your New Page</h1>+ {/* Your content */}+ </div>+ );+}+```++## Transactional Emails++The storefront can render and send its own order, shipment, and account emails with react-email and Resend, driven by Spree webhooks. See the dedicated [Transactional Emails](/v5/developer/storefront/nextjs/emails) guide.++## Building a Custom Storefront++If you prefer to build from scratch instead of using the starter, you can use the `@spree/sdk` package directly in any Next.js application. The storefront's `src/lib/spree/` directory contains reusable helpers for cookie-based auth, locale resolution, middleware, and webhook verification that you can copy into your own project.diff --git a/docs/v5/developer/storefront/nextjs/deployment.mdx b/docs/v5/developer/storefront/nextjs/deployment.mdxnew file mode 100644index 0000000000..7230bf300b--- /dev/null+++ b/docs/v5/developer/storefront/nextjs/deployment.mdx@@ -0,0 +1,164 @@+---+title: Deployment+description: Deploy the Spree Next.js Storefront to Vercel, Docker, or any Node.js host+canonical: "https://spreecommerce.org/docs/developer/storefront/nextjs/deployment"+---++## Environment Variables++At minimum, set `SPREE_API_URL` and `SPREE_PUBLISHABLE_KEY` in your hosting platform's dashboard or `.env` file. See [Environment Variables](/v5/developer/storefront/nextjs/environment-variables) for the full reference — analytics, error tracking, wholesale, emails, and SEO.++## Production Build++```bash+npm run build+npm start+```++The build output is a standalone Next.js application. The `npm start` command starts the production server.++## Vercel++Vercel is the recommended deployment platform for Next.js applications.++### One-Click Deploy++1. Push your code to GitHub+2. Go to [vercel.com/new](https://vercel.com/new) and import your repository+3. Add environment variables:+ - `SPREE_API_URL` and `SPREE_PUBLISHABLE_KEY` (required)+ - `SPREE_WEBHOOK_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM` — for [transactional emails](/v5/developer/storefront/nextjs/emails)+ - `GTM_ID` — optional, Google Tag Manager+ - `SENTRY_DSN`, `SENTRY_ORG`, `SENTRY_PROJECT`, `SENTRY_AUTH_TOKEN` — optional, error tracking with readable stack traces++ See the [Environment Variables reference](/v5/developer/storefront/nextjs/environment-variables) for the full list.+4. Click **Deploy**++Vercel automatically detects the Next.js framework and configures the build settings.++### Vercel CLI++```bash+npm i -g vercel+vercel+```++### Preview Deployments++Every pull request gets a unique preview URL, making it easy to test storefront changes before merging. Add your Spree API environment variables to the Vercel project settings so previews connect to your staging API.++## Docker++A multi-stage `Dockerfile` ships at the repo root. It uses Next.js standalone output to produce a small (~240 MB) image on `node:22-alpine`, runs as a non-root user, and exposes port `3001`.++<Note>+ `SPREE_API_URL` and `SPREE_PUBLISHABLE_KEY` are required at **build time** — the storefront prerenders pages against the Spree API. Point them at a Spree instance reachable from wherever you run `docker build` (hosted Spree, a tunnel, or `host.docker.internal` for a local backend on Docker Desktop).+</Note>++Build and run:++```bash+docker build \+ --build-arg SPREE_API_URL=https://your-spree.example.com \+ --build-arg SPREE_PUBLISHABLE_KEY=your_publishable_key \+ -t spree-storefront .++docker run -p 3001:3001 --env-file .env.local spree-storefront+```++### Sentry source maps at build time++`SENTRY_AUTH_TOKEN` is passed via a BuildKit secret so it never lands in image layers or the build cache. The other Sentry vars are regular build args:++```bash+SENTRY_AUTH_TOKEN=... docker build \+ --build-arg SPREE_API_URL=... \+ --build-arg SPREE_PUBLISHABLE_KEY=... \+ --build-arg SENTRY_DSN=... \+ --build-arg SENTRY_ORG=... \+ --build-arg SENTRY_PROJECT=... \+ --secret id=sentry_auth_token,env=SENTRY_AUTH_TOKEN \+ -t spree-storefront .+```++### Building against a local Spree backend++On Docker Desktop (macOS/Windows), reach the host's Spree via `host.docker.internal`:++```bash+docker build \+ --add-host=host.docker.internal:host-gateway \+ --build-arg SPREE_API_URL=http://host.docker.internal:3000 \+ --build-arg SPREE_PUBLISHABLE_KEY=your_publishable_key \+ -t spree-storefront .++docker run -p 3001:3001 \+ --add-host=host.docker.internal:host-gateway \+ --env-file .env.local \+ spree-storefront+```++## Self-Hosted Node.js++For any platform that supports Node.js (Render, Railway, Fly.io, AWS, etc.):++1. Install dependencies and build:++```bash+npm ci+npm run build+```++2. Start the production server:++```bash+npm start+```++The server listens on port `3001`. Set the `PORT` environment variable to change it.++## CI/CD++### GitHub Actions++```yaml+name: Deploy Storefront+on:+ push:+ branches: [main]++jobs:+ deploy:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-node@v4+ with:+ node-version: 20+ cache: npm++ - run: npm ci+ - run: npm run build++ # Add your deployment step here+ # Example for Vercel:+ # - uses: amondnet/vercel-action@v25+ # with:+ # vercel-token: ${{ secrets.VERCEL_TOKEN }}+ # vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}+ # vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}+ # vercel-args: --prod+```++## Performance Checklist++Before going to production, verify:++- **API URL** points to your production Spree instance (not `localhost`)+- **HTTPS** is enabled on both the storefront and the Spree API+- **CORS** is configured on your Spree API to allow requests from your storefront domain+- **Sentry** is configured for error monitoring (`SENTRY_DSN`)+- **GTM/GA4** is set up for analytics (`GTM_ID`)+- **Cookie security** — the storefront uses `secure: true` for cookies in production (`NODE_ENV=production`)+- **Caching** — Next.js cache tags are used for efficient revalidation; review your caching strategy for high-traffic storesdiff --git a/docs/v5/developer/storefront/nextjs/emails.mdx b/docs/v5/developer/storefront/nextjs/emails.mdxnew file mode 100644index 0000000000..c1661ffac3--- /dev/null+++ b/docs/v5/developer/storefront/nextjs/emails.mdx@@ -0,0 +1,87 @@+---+title: Transactional Emails+description: Render and send order, shipment, and account emails from the Spree Next.js Storefront with react-email, Resend, and Spree webhooks+canonical: "https://spreecommerce.org/docs/developer/storefront/nextjs/emails"+---++The storefront can own its customer-facing transactional emails instead of the Spree backend. Emails are rendered with [react-email](https://react.email) and sent via [Resend](https://resend.com); the Spree backend delivers order, shipment, and account events to the storefront over [webhooks](/v5/developer/core-concepts/webhooks).++```+Spree Backend → Webhook POST → /api/webhooks/spree → render email → send via Resend+(signed HMAC) (signature verified) (react-email) (or write to disk in dev)+```++## Templates++Email templates are React components in `src/lib/emails/`:++| File | Event | Description |+|------|-------|-------------|+| `order-confirmation.tsx` | `order.completed` | Items, totals, addresses, delivery method |+| `order-canceled.tsx` | `order.canceled` | Cancellation notice with items |+| `shipment-shipped.tsx` | `order.shipped` | Tracking number and link |+| `password-reset.tsx` | `customer.password_reset_requested` | Reset button and fallback link |++Customize a template by editing its file directly — they use `@react-email/components` for email-safe layout primitives.++## Previewing++Run the storefront in development and open [http://localhost:3001/dev/emails](http://localhost:3001/dev/emails):++```bash+npm run dev+```++Each template renders with sample data via `@react-email/render`. The route is gated to non-production environments.++## Configuration++Add these to `.env.local`:++```env+SPREE_WEBHOOK_SECRET=your_webhook_endpoint_secret_key+RESEND_API_KEY=re_your_resend_api_key # production only+EMAIL_FROM=Your Store <[email protected]> # production only+```++In development no `RESEND_API_KEY` is needed — emails are written to `.next/emails/` as HTML files with a `file://` link logged to the console.++## Webhook Handler++The webhook route (`src/app/api/webhooks/spree/route.ts`) wires events to handlers with `createWebhookHandler` from `src/lib/spree/webhooks`. Signature verification and event routing are handled for you:++```typescript+import { createWebhookHandler } from '@/lib/spree/webhooks'++const handler = createWebhookHandler({+ secret: process.env.SPREE_WEBHOOK_SECRET!,+ handlers: {+ 'order.completed': handleOrderCompleted,+ 'order.canceled': handleOrderCanceled,+ 'order.shipped': handleOrderShipped,+ 'customer.password_reset_requested': handlePasswordReset,+ },+})+```++To add a new email type:++1. Create a template in `src/lib/emails/`.+2. Add a handler function in `src/lib/webhooks/handlers.ts`.+3. Register the event in `route.ts`.+4. Subscribe to the event in **Spree Admin → Settings → Developers → Webhooks**.++## Setup++1. **Create a webhook endpoint** in Spree Admin → Settings → Developers → Webhooks. Subscribe to `order.completed`, `order.canceled`, `order.shipped`, and `customer.password_reset_requested`, and copy the secret key into `SPREE_WEBHOOK_SECRET`.++2. **Receive webhooks locally.** Expose the storefront with a public URL so Spree can reach it — the simplest option is a [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/):++ ```bash+ brew install cloudflared+ cloudflared tunnel --url http://localhost:3001+ ```++ Use the tunnel URL as the webhook endpoint URL in Spree Admin.++For the backend perspective on delivering these events, see [Sending out Emails](/v5/developer/deployment/emails).diff --git a/docs/v5/developer/storefront/nextjs/environment-variables.mdx b/docs/v5/developer/storefront/nextjs/environment-variables.mdxnew file mode 100644index 0000000000..ab7b9fc409--- /dev/null+++ b/docs/v5/developer/storefront/nextjs/environment-variables.mdx@@ -0,0 +1,93 @@+---+title: Environment Variables+description: Every environment variable the Spree Next.js Storefront reads, with defaults and when to set it+canonical: "https://spreecommerce.org/docs/developer/storefront/nextjs/environment-variables"+---++Configuration lives in `.env.local` (copy `.env.example` to start). Variables **without** a `NEXT_PUBLIC_` prefix are server-side only and never reach the browser; `NEXT_PUBLIC_` variables are inlined into the client bundle at build time, so only put non-secret values there.++## Required++| Variable | Description |+|----------|-------------|+| `SPREE_API_URL` | Your Spree API endpoint (e.g. `http://localhost:3000` in dev, `https://api.mystore.com` in production) |+| `SPREE_PUBLISHABLE_KEY` | Publishable API key from your Spree admin |++<Note>+ In a Docker build these two are also required at **build time** — the storefront prerenders pages against the Spree API. See [Deployment](/v5/developer/storefront/nextjs/deployment).+</Note>++## Store defaults++Used by the middleware for initial redirects before API data loads, and as build-time fallbacks for sitemap/SEO generation.++| Variable | Description | Default |+|----------|-------------|---------|+| `NEXT_PUBLIC_DEFAULT_COUNTRY` | Default country ISO code — should match your store's `default_country_iso` | `us` |+| `NEXT_PUBLIC_DEFAULT_LOCALE` | Default locale code — should match your store's `default_locale` | `en` |+| `NEXT_PUBLIC_SITE_URL` | Public site URL, used for sitemap and `robots.txt` generation (e.g. `https://mystore.com`) | _(required for sitemap)_ |+| `NEXT_PUBLIC_STORE_NAME` | Store name used in metadata fallbacks | `Spree Store` |+| `NEXT_PUBLIC_STORE_DESCRIPTION` | Store description used in metadata fallbacks | _(sample text)_ |++## SEO & social++Optional overrides for site metadata and the Organization JSON-LD. When unset, values fall back to store settings from the Spree API.++| Variable | Description |+|----------|-------------|+| `STORE_SEO_TITLE` | Default `<title>` |+| `STORE_META_DESCRIPTION` | Default meta description |+| `STORE_META_KEYWORDS` | Default meta keywords |+| `STORE_TWITTER` | Twitter/X handle or URL |+| `STORE_FACEBOOK` | Facebook page URL |+| `STORE_INSTAGRAM` | Instagram URL |+| `STORE_LOGO_URL` | Logo URL for Organization JSON-LD |+| `STORE_SUPPORT_EMAIL` | Customer support email |++## Wholesale B2B portal++The [wholesale portal](/v5/developer/storefront/nextjs/wholesale) is an opt-in addon, off by default.++| Variable | Description | Default |+|----------|-------------|---------|+| `SPREE_WHOLESALE_CHANNEL` | Enable switch — the code of a gated Spree channel to bind the `/wholesale` surface to. Unset means DTC-only: every wholesale entry point is hidden and the routes 404 | _(disabled)_ |+| `SPREE_WHOLESALE_PUBLISHABLE_KEY` | Channel-scoped publishable key for the wholesale surface. Optional — the channel header selects the channel, so this falls back to `SPREE_PUBLISHABLE_KEY` | _(falls back to `SPREE_PUBLISHABLE_KEY`)_ |++## Transactional emails++See the [Transactional Emails](/v5/developer/storefront/nextjs/emails) guide for the full setup.++| Variable | Description | Default |+|----------|-------------|---------|+| `SPREE_WEBHOOK_SECRET` | Webhook endpoint secret key that signs incoming Spree webhooks | _(disabled)_ |+| `RESEND_API_KEY` | [Resend](https://resend.com) API key for sending emails in production | _(dev: writes to disk)_ |+| `EMAIL_FROM` | "From" address for transactional emails (e.g. `Store <[email protected]>`) | `[email protected]` |++## Payments++Publishable keys for client-side payment SDKs, read when the matching gateway is enabled. Set the key for whichever provider(s) you use.++| Variable | Description |+|----------|-------------|+| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key (`pk_…`) |++## Analytics++| Variable | Description | Default |+|----------|-------------|---------|+| `GTM_ID` | Google Tag Manager container ID (e.g. `GTM-XXXXXXX`). Leave empty to disable | _(disabled)_ |++## Error tracking (Sentry)++| Variable | Description | Default |+|----------|-------------|---------|+| `SENTRY_DSN` | Sentry DSN — set to enable error tracking (e.g. `https://[email protected]/0`) | _(disabled)_ |+| `SENTRY_ORG` | Sentry organization slug (for source map uploads) | _(none)_ |+| `SENTRY_PROJECT` | Sentry project slug (for source map uploads) | _(none)_ |+| `SENTRY_AUTH_TOKEN` | Sentry auth token (for source map uploads in CI) | _(none)_ |+| `SENTRY_SEND_DEFAULT_PII` | Send PII (IP addresses, cookies, user data) to Sentry server-side | `false` |+| `NEXT_PUBLIC_SENTRY_SEND_DEFAULT_PII` | Send PII to Sentry client-side | `false` |++<Warning>+ PII collection is disabled by default. Only set the `SENTRY_SEND_DEFAULT_PII` variables to `true` if you have appropriate user consent or a privacy policy covering this data.+</Warning>diff --git a/docs/v5/developer/storefront/nextjs/multi-region.mdx b/docs/v5/developer/storefront/nextjs/multi-region.mdxnew file mode 100644index 0000000000..29aedfdb22--- /dev/null+++ b/docs/v5/developer/storefront/nextjs/multi-region.mdx@@ -0,0 +1,76 @@+---+title: Multi-Region+description: How the Spree Next.js Storefront serves multiple countries, currencies, and languages from a single deployment via URL segments and edge middleware+canonical: "https://spreecommerce.org/docs/developer/storefront/nextjs/multi-region"+---++The storefront serves multiple countries, currencies, and languages from a single deployment. Region is encoded in the URL, detected automatically for first-time visitors by middleware, and mapped to a [Spree Market](/v5/developer/core-concepts/markets) — the model that bundles a country, currency, and locale — so every server-side fetch resolves prices and content for the right region.++## URL structure++Every route is prefixed with a country and locale segment:++```+/us/en/products # US market, English+/de/de/products # German market, German+/uk/en/products # UK market, English+```++The `[country]` and `[locale]` segments are the first two dynamic params of the App Router tree (`src/app/[country]/[locale]/…`). Because region lives in the path, every URL is shareable and independently cacheable, and search engines index each region separately.++## The middleware++A visitor who lands on a bare path (no region prefix) is redirected to the correct `/{country}/{locale}/…` URL by an edge middleware. It's wired in `src/proxy.ts`:++```typescript+import { createSpreeMiddleware } from '@/lib/spree/middleware'+import { getDefaultCountry, getDefaultLocale } from '@/lib/store'++export const proxy = createSpreeMiddleware({+ defaultCountry: getDefaultCountry(),+ defaultLocale: getDefaultLocale(),+})++export const config = {+ matcher: ['/((?!api/|_next/static|_next/image|favicon.ico|.*\\..*$).*)'],+}+```++`createSpreeMiddleware` (from `src/lib/spree`) does three things:++- **Redirects** bare paths to `/{country}/{locale}/…`.+- **Detects** the visitor's country and locale (see below).+- **Syncs** `spree_country` and `spree_locale` cookies with the URL segments, so server-side fetches via `getLocaleOptions()` resolve the same market the URL asks for.++Requests that already carry a `/{country}/{locale}` prefix pass through untouched — the middleware only refreshes the cookies to match.++### Detection chain++For a request without a region prefix, each value is resolved from the first source that has it:++| Value | Resolution order |+|-------|------------------|+| **Country** | `spree_country` cookie → `x-vercel-ip-country` / `cf-ipcountry` geo header → default |+| **Locale** | `spree_locale` cookie → `Accept-Language` header (primary tag) → default |++Geo headers are set by the hosting edge — `x-vercel-ip-country` on Vercel, `cf-ipcountry` behind Cloudflare. On a host that provides neither, detection falls back to `Accept-Language` for locale and the configured default for country. A returning visitor's cookie always wins, so a manual region change sticks.++### Configuration++`createSpreeMiddleware` accepts:++| Option | Description | Default |+|--------|-------------|---------|+| `defaultCountry` | Fallback country ISO when nothing else matches | `us` |+| `defaultLocale` | Fallback locale when nothing else matches | `en` |+| `staticRoutes` | Path prefixes to skip | `['/_next', '/api', '/dev', '/favicon.ico']` |++In the storefront these defaults come from `NEXT_PUBLIC_DEFAULT_COUNTRY` and `NEXT_PUBLIC_DEFAULT_LOCALE` (see [Environment Variables](/v5/developer/storefront/nextjs/environment-variables)). The `matcher` in `proxy.ts` additionally excludes API routes, Next.js internals, and any path with a file extension, so the middleware only runs on page navigations.++## Switching regions++The `CountrySwitcher` component (in `src/components/layout/`) lets a visitor change region manually. Selecting a new region navigates to the matching URL prefix; the middleware then updates the `spree_country` / `spree_locale` cookies so the choice persists across future visits.++## How region reaches the data layer++Region-aware reads don't take a country/locale argument — they call `getLocaleOptions()` from `src/lib/spree`, which reads the `spree_country` / `spree_locale` cookies the middleware keeps in sync with the URL. That value is passed to `@spree/sdk`, which sends it to the Store API so prices, currency, and translated content come back for the right [market](/v5/developer/core-concepts/markets). See [Architecture](/v5/developer/storefront/nextjs/architecture) for the wider server-first data flow.diff --git a/docs/v5/developer/storefront/nextjs/quickstart.mdx b/docs/v5/developer/storefront/nextjs/quickstart.mdxnew file mode 100644index 0000000000..602101f115--- /dev/null+++ b/docs/v5/developer/storefront/nextjs/quickstart.mdx@@ -0,0 +1,100 @@+---+title: Quickstart+description: Get started with the Spree Next.js Storefront+canonical: "https://spreecommerce.org/docs/developer/storefront/nextjs/quickstart"+---++The [Spree Storefront](https://github.com/spree/storefront) is a production-ready, headless e-commerce storefront built with Next.js 16, React 19, and the Spree Commerce API v3.++## Tech Stack++- **Next.js 16** - App Router, Server Actions, Turbopack+- **React 19** - Server Components+- **Tailwind CSS 4** - Utility-first styling+- **TypeScript 5** - Full type safety+- **[@spree/sdk](https://github.com/spree/spree/tree/main/packages/sdk)** - Official Spree Commerce SDK+- **Sentry** - Error tracking and performance monitoring++## Features++- **Server-First Architecture** - All API calls happen server-side, API keys never exposed to the browser+- **Secure Authentication** - JWT tokens stored in httpOnly cookies+- **Product Catalog** - Browse, search, and filter with faceted navigation+- **Shopping Cart** - Server-side state management+- **Multi-Step Checkout** - Guest and signed-in users, multi-fulfillment, coupon codes, gift cards, store credit+- **Stripe Payments** - Credit Cards, Apple Pay, Google Pay, Klarna, Affirm, SEPA and more via [Spree Stripe](https://github.com/spree/spree_stripe)+- **Google Tag Manager** and **GA4 Ecommerce** event tracking+- **Customer Account** - Profile, order history, address book, gift cards, saved payment methods+- **Multi-Region** - Country and currency switching via URL segments+- **Responsive Design** - Mobile-first Tailwind CSS++## Prerequisites++- Node.js 20++- A running Spree Commerce 5.4+ instance++## Installation++### Recommended: create-spree-app++The fastest way to get a full project — Spree backend, this Next.js storefront, and the `spree` CLI, wired together — is [`create-spree-app`](/v5/developer/create-spree-app/quickstart):++```bash+npx create-spree-app my-store+```++The storefront is included by default (pass `--no-storefront` to skip it). It's scaffolded into `apps/storefront/` with its `.env.local` already pointing at the backend, so it boots against real data with no manual key wiring.++### Standalone++To run the storefront on its own — against an existing Spree backend, or to work on the storefront repo directly — clone it and install:++```bash+git clone https://github.com/spree/storefront.git+cd storefront+npm install+```++Then follow [Configuration](#configuration) to point it at your Spree API. If you plan to customize and track upstream changes, [fork first](/v5/developer/storefront/nextjs/customization#tracking-upstream-updates).++## Configuration++Copy the environment file:++```bash+cp .env.local.example .env.local+```++Update `.env.local` with your Spree API credentials:++```env+SPREE_API_URL=http://localhost:3000+SPREE_PUBLISHABLE_KEY=your_publishable_api_key_here+```++<Note>+ These are server-side only variables — no `NEXT_PUBLIC_` prefix needed since all API calls happen in Server Actions.+</Note>++See [Deployment](/v5/developer/storefront/nextjs/deployment) for all optional environment variables (Sentry, GTM, etc.).++## Development++```bash+npm run dev+```++Open [http://localhost:3001](http://localhost:3001) in your browser.++<Note>+ Testing Apple Pay / Google Pay locally needs a public HTTPS URL. See [Wallet Payments in Development](/v5/developer/storefront/nextjs/wallet-payments).+</Note>++## Production Build++```bash+npm run build+npm start+```++See the [Deployment](/v5/developer/storefront/nextjs/deployment) guide for Vercel, Docker, and other hosting options.diff --git a/docs/v5/developer/storefront/nextjs/testing.mdx b/docs/v5/developer/storefront/nextjs/testing.mdxnew file mode 100644index 0000000000..c4f01b8306--- /dev/null+++ b/docs/v5/developer/storefront/nextjs/testing.mdx@@ -0,0 +1,86 @@+---+title: Testing+description: Run the Spree Next.js Storefront's unit tests with Vitest and its end-to-end suite with Playwright against a real Spree backend+canonical: "https://spreecommerce.org/docs/developer/storefront/nextjs/testing"+---++The storefront ships two test layers: fast unit/integration tests with Vitest, and a browser end-to-end suite with Playwright that runs against a real Spree backend booted in Docker.++## Unit & integration (Vitest)++```bash+npm test # one-shot+npm run test:watch # watch mode+```++## End-to-end (Playwright)++The E2E suite drives a browser against a real Spree backend. `npm run e2e:up` boots the backend — Postgres, Redis, and the official `ghcr.io/spree/spree:latest` image from `e2e-backend/docker-compose.yml` — then seeds it and mints an API key through the official [`@spree/cli`](/v5/developer/cli/quickstart) (`spree seed`, `spree sample-data`, `spree api-key create`), installed as a dev dependency. No `create-spree-app` setup is required.++```bash+# 1. Export a Stripe test-mode key pair from your own Stripe sandbox.+# Both keys must belong to the same account — Stripe no longer+# publishes a working sample secret key, and a mismatched pair makes+# the checkout payment step fail.+export STRIPE_PUBLISHABLE_KEY=pk_test_…+export STRIPE_SECRET_KEY=sk_test_…++# 2. Boot Spree + Postgres + Redis, seed sample data, register a Stripe+# payment gateway, mint a publishable key, and write .env.e2e.+npm run e2e:up++# 3. Run the suite. Playwright boots `next dev` against .env.e2e.+npm run test:e2e++# Optional: interactive UI mode.+npm run test:e2e:ui++# Tear everything down.+npm run e2e:down+```++The checkout test pays with card `4242 4242 4242 4242` through Stripe's [test mode](https://docs.stripe.com/keys). PaymentIntents land in whichever Stripe test account owns the keys you exported.++### CI++In CI, set `STRIPE_SECRET_KEY` as a repository secret and `STRIPE_PUBLISHABLE_KEY` as a repository variable (**Settings → Secrets and variables → Actions**). The E2E job skips itself on fork PRs, where GitHub never exposes repository secrets.++## Testing against a customized backend++<Note>+ By default the E2E suite runs against the stock official Spree image (`ghcr.io/spree/spree:latest`), so it verifies the storefront against a **vanilla Spree** — not a backend with your own extensions, serializers, or seed data.+</Note>++The E2E stack reads a `SPREE_IMAGE` env var and falls back to the stock image when it's unset. Set it to any image that exposes the Store API on the container's port `3000`, and the suite runs against that backend instead.++### Your own Spree image++If you already publish a customized Spree image:++```bash+SPREE_IMAGE=ghcr.io/your-org/your-spree:latest npm run e2e:up+npm run test:e2e+```++### A `create-spree-app` project's backend++A project scaffolded with [`create-spree-app`](/v5/developer/create-spree-app/quickstart) has its customizable Spree in `backend/` (built from `backend/Dockerfile`) and this storefront in `apps/storefront/`. Build that backend into a local image and point the suite at it — this is what tests the storefront against the **exact Spree you deploy**, extensions and all:++```bash+# From the project root — build the customized backend image+docker build -t project-spree:e2e ./backend++# From apps/storefront — run E2E against it+cd apps/storefront+SPREE_IMAGE=project-spree:e2e npm run e2e:up+npm run test:e2e+npm run e2e:down+```++<Note>+ New `create-spree-app` projects wire this into the generated storefront CI workflow automatically — the workflow builds `backend/Dockerfile` and runs the storefront E2E against that image rather than stock Spree.+</Note>++### Interactive / manual++To click through the storefront against a running backend (no E2E harness), point it there directly: set `SPREE_API_URL` and `SPREE_PUBLISHABLE_KEY` in `.env.local` (see [Environment Variables](/v5/developer/storefront/nextjs/environment-variables)) and run `npm run dev`.diff --git a/docs/v5/developer/storefront/nextjs/wallet-payments.mdx b/docs/v5/developer/storefront/nextjs/wallet-payments.mdxnew file mode 100644index 0000000000..f23d2f7b75--- /dev/null+++ b/docs/v5/developer/storefront/nextjs/wallet-payments.mdx@@ -0,0 +1,53 @@+---+title: Wallet Payments in Development+description: Test Apple Pay and Google Pay against a local Spree Next.js Storefront using a public HTTPS URL+canonical: "https://spreecommerce.org/docs/developer/storefront/nextjs/wallet-payments"+---++Apple Pay and Google Pay require HTTPS **and a publicly-reachable URL** — Stripe verifies the payment method domain from the internet, so `localhost` and locally-trusted certificates (e.g. `mkcert` + `lvh.me`) won't pass domain verification. The simplest way to expose your local storefront with a valid public HTTPS URL is [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/).++## Setup++1. Install `cloudflared`:++ ```bash+ brew install cloudflared+ ```++2. Start the dev server normally (HTTP on port 3001):++ ```bash+ npm run dev+ ```++3. In a second terminal, expose it through a quick tunnel:++ ```bash+ cloudflared tunnel --url http://localhost:3001+ ```++ The output will contain a URL like `https://<random-words>.trycloudflare.com`.++4. Register that URL in your [Stripe Payment method domains](https://dashboard.stripe.com/settings/payment_methods/domains).++5. Open the tunnel URL in your browser and test the Express Checkout buttons in the cart.++## Stable tunnel URLs++`next.config.ts` already allows `*.trycloudflare.com` via `allowedDevOrigins`, so quick tunnels work out of the box. Every time you restart `cloudflared tunnel --url ...` you get a new random subdomain — if you need a stable URL (to avoid re-registering in Stripe on each run), set up a [named tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/#using-named-tunnels) on your own domain.++## The Spree backend must also be publicly reachable++The storefront's server-side fetches go to `SPREE_API_URL`, but image URLs and a few other backend-served paths (e.g. the Apple Pay domain-verification file under `/.well-known/apple-developer-merchantid-domain-association`) are fetched by the browser directly and must resolve from the public internet.++Point `SPREE_API_URL` at a hosted Spree (e.g. `*.spree.sh`, `*.vendo.dev`, your own staging) or expose your local Spree with another tunnel:++```bash+cloudflared tunnel --url http://localhost:3000+```++When tunneling a local Rails app, allow the tunnel host in the backend's `.env`:++```env+RAILS_DEVELOPMENT_HOSTS=.trycloudflare.com+```diff --git a/docs/v5/developer/storefront/nextjs/wholesale.mdx b/docs/v5/developer/storefront/nextjs/wholesale.mdxnew file mode 100644index 0000000000..a6606dc404--- /dev/null+++ b/docs/v5/developer/storefront/nextjs/wholesale.mdx@@ -0,0 +1,85 @@+---+title: Wholesale Portal+description: The opt-in B2B wholesale surface and how channel-backed surfaces work+canonical: "https://spreecommerce.org/docs/developer/storefront/nextjs/wholesale"+---++## What the Wholesale Portal Is++The storefront ships an optional **wholesale portal** at `/wholesale` — a gated B2B surface for approved trade buyers. It runs on a separate Spree sales channel but shares the same storefront app and Spree backend as the public direct-to-consumer (DTC) store, so a single deployment serves both audiences: the open catalog for shoppers and a login-gated trade catalog with volume pricing for wholesale buyers.++The portal is an **opt-in addon**. It is off by default; a DTC-only storefront never renders any wholesale UI.++<Note>+The wholesale portal is a **reference implementation**, not a fixed feature. It demonstrates one shape — a gated B2B surface running *alongside* an open DTC store — but the same building blocks (channels, [surfaces](#surfaces-and-channel-switching), and [access gating](#gating-modes)) support the whole spectrum. You can invert the default and make the storefront closed or limited: gate the *primary* DTC channel with `login_required` or `prices_hidden` for a members-only or invite-only shop, drop the public catalog entirely and ship a login-first B2B storefront, or run several gated channels with no open surface at all. Treat this page as a worked example to adapt, not a prescription — the storefront is yours to reshape.+</Note>++## Surfaces and Channel Switching++A **surface** is a distinct sales context backed by its own Spree [channel](/v5/developer/core-concepts/channels). The storefront models two out of the box — `dtc` (the public storefront) and `wholesale` (the trade portal) — but the mechanism is general: any channel on your backend can back its own surface.++The surface selects which SDK client a request goes through. A channel-bound client sends the channel code on every request via the `X-Spree-Channel` header, and the Store API [resolves the request against that channel](/v5/developer/core-concepts/channels#resolution-at-request-time) — its catalog, pricing, and access rules. In the SDK this is the `channel` client option:++```ts+import { createClient } from '@spree/sdk'++const wholesaleClient = createClient({+ baseUrl: process.env.SPREE_API_URL,+ publishableKey: process.env.SPREE_PUBLISHABLE_KEY,+ channel: 'wholesale', // sent as X-Spree-Channel on every request+})+```++Alternatively, a **channel-bound publishable key** carries the channel server-side: when a key is scoped to a channel on the backend, the API assigns that channel to the request without needing the header. Either path works; the header is the simplest and is what the storefront uses by default.++Because each surface has its own client, cart cookies, and cache keys, a customer can hold an open DTC cart and an open wholesale cart at the same time without them mixing. The customer session (JWT) is shared — it's the same person signing in — so only the cart splits, never the auth.++To add your own channel-backed surface, follow the same pattern: create the channel on the backend, add a client bound to its code, and thread the surface through the routes that should target it.++## Enabling Wholesale++Wholesale turns on through a single environment variable:++- **`SPREE_WHOLESALE_CHANNEL`** — the enable switch. Set it to the code of a gated channel on your backend (e.g. `wholesale`). There is **no default**: when it is unset, the storefront runs DTC-only — the wholesale nav link, footer link, and homepage section are hidden, and every `/wholesale` route returns 404.+- **`SPREE_WHOLESALE_PUBLISHABLE_KEY`** — optional. The channel header alone selects the channel, so this falls back to `SPREE_PUBLISHABLE_KEY`. Set it only to bind a channel-scoped publishable key.++The backend must have a [channel](/v5/developer/core-concepts/channels) whose code matches `SPREE_WHOLESALE_CHANNEL`. Its [`storefront_access`](/v5/developer/core-concepts/channels#storefront-access-gating) posture decides how much a guest can see — the portal supports both `login_required` (guests are walled off entirely) and `prices_hidden` (guests browse the catalog but not prices). See [Gating Modes](#gating-modes) below. Spree installs seed a `login_required` wholesale channel by default; switching to `prices_hidden` is a single flag on that same channel — no new channel or seed data.++## How Gating Works End to End++Two independent checks gate the portal — one at the **channel** (how much of the catalog a guest may see), one at the **customer** (whether a buyer may transact at trade pricing). The channel check is set by the channel's [gating mode](#gating-modes); the customer check is always the same.++**Channel access** is enforced by the Store API, not the storefront — the storefront can't loosen it. Depending on the channel's `storefront_access` posture, a guest is either rejected outright (`login_required`) or served the catalog with money fields returned as `null` (`prices_hidden`). This is a general channel feature; see [Channels → Storefront Access Gating](/v5/developer/core-concepts/channels#storefront-access-gating) for how it's resolved and enforced.++**Buyer approval.** Being logged in isn't enough; a buyer must be *approved*. Approval is membership in the **Wholesale** [customer group](/v5/developer/core-concepts/pricing#customer-group-rule) — an admin adds an applicant to the group to approve them. The storefront reads `customer_groups` on `customers/me` and branches accordingly:++- **Guest** — sees the sign-in / apply wall (`login_required`), or the read-only catalog with sign-in-for-pricing prompts (`prices_hidden`).+- **Signed in, not in the group** — sees an application-pending state. Signing in never skips approval: an authenticated but unapproved buyer cannot transact under either mode.+- **Signed in and in the group** — gets the full portal: trade catalog, quick order, and the wholesale cart.++**Trade pricing** is unlocked by volume. The seeded model grants a trade price once a line reaches a minimum quantity of the same item (10 or more per item in the sample data). The applicable volume rule lives on a backend [Price List](/v5/developer/core-concepts/pricing#price-lists); the storefront surfaces the trade price the API returns for a qualifying quantity.++## Gating Modes++A channel's `storefront_access` posture is one of three values. The wholesale portal supports the two gated modes; the third describes a fully public channel like DTC.++| Mode | Guest sees catalog | Guest sees prices | Guest can order |+|---|---|---|---|+| `login_required` | No — hard `401`, sign-in wall | No | No |+| `prices_hidden` | Yes — read-only | No — "sign in for pricing" | No — "sign in to order" |+| `public` | Yes | Yes | Yes (subject to guest checkout) |++**`login_required`** is the strictest posture and the seeded default. The Store API rejects any unauthenticated request to the channel with `401`, so a guest can't read wholesale catalog or pricing at all. The storefront shows the sign-in / apply wall in place of every gated page.++**`prices_hidden`** opens the catalog to guests while keeping pricing private. The channel doesn't reject unauthenticated requests, but the API serializes every money field as `null` for a guest. In the portal, a guest browses the catalog and product pages read-only: each price renders a **"sign in for pricing"** prompt, and add-to-cart becomes **"sign in to order."** Ordering surfaces (cart, quick order) still require sign-in — a guest is redirected to the sign-in flow rather than shown an empty wholesale cart. Approval is unchanged: signing in reveals list prices, and joining the Wholesale group unlocks trade pricing. This mode suits a trade catalog you want discoverable (for SEO or lead generation) without exposing negotiated pricing.++**`public`** is an ungated channel — the posture the DTC store runs on. It's listed here for completeness; a wholesale channel would not normally use it.++Switching a wholesale channel between the two supported modes is a single change to [`storefront_access`](/v5/developer/core-concepts/channels#storefront-access-gating) on the backend — set on the channel, or inherited from the [store's default](/v5/developer/core-concepts/stores#storefront-access-defaults). Nothing in the storefront needs redeploying — the portal reads the channel's posture at request time and adapts. Login and signup always run through the same approval flow regardless of mode.++## Related Documentation++- [Channels](/v5/developer/core-concepts/channels) — The sales channel that backs the wholesale surface, and the general [Storefront Access Gating](/v5/developer/core-concepts/channels#storefront-access-gating) mechanism the portal builds on+- [Stores](/v5/developer/core-concepts/stores) — Store-level [defaults](/v5/developer/core-concepts/stores#storefront-access-defaults) that channels inherit+- [Pricing](/v5/developer/core-concepts/pricing) — [Price Lists](/v5/developer/core-concepts/pricing#price-lists) and the [Customer Group Rule](/v5/developer/core-concepts/pricing#customer-group-rule) behind approval and trade pricing+- [Store SDK: Configuration](/v5/developer/sdk/configuration) — `setChannel` and the channel client option used to bind a surfacediff --git a/docs/developer/storefront/rails/blocks.mdx b/docs/v5/developer/storefront/rails/blocks.mdxsimilarity index 95%rename from docs/developer/storefront/rails/blocks.mdxrename to docs/v5/developer/storefront/rails/blocks.mdxindex 5f4e5f248b..c67c23e60b 100644--- a/docs/developer/storefront/rails/blocks.mdx+++ b/docs/v5/developer/storefront/rails/blocks.mdx@@ -1,9 +1,10 @@---title: "Blocks"description: "Learn how to utilize blocks to build your Spree Storefront"+canonical: "https://spreecommerce.org/docs/v5/developer/storefront/rails/blocks"----Blocks are the lowest level of components in Spree Storefront. They are nested inside [sections](/developer/storefront/rails/sections) and represent individual content elements like headings, text, buttons, and images.+Blocks are the lowest level of components in Spree Storefront. They are nested inside [sections](/v5/developer/storefront/rails/sections) and represent individual content elements like headings, text, buttons, and images.## How Blocks Work@@ -280,6 +281,6 @@ block.asset.attached?## Related Documentation-- [Sections](/developer/storefront/rails/sections) - Parent containers for blocks-- [Links](/developer/storefront/rails/links) - Adding links to blocks-- [Media](/developer/core-concepts/media) - Working with images+- [Sections](/v5/developer/storefront/rails/sections) - Parent containers for blocks+- [Links](/v5/developer/storefront/rails/links) - Adding links to blocks+- [Media](/v5/developer/core-concepts/media) - Working with imagesdiff --git a/docs/developer/storefront/rails/custom-css.mdx b/docs/v5/developer/storefront/rails/custom-css.mdxsimilarity index 96%rename from docs/developer/storefront/rails/custom-css.mdxrename to docs/v5/developer/storefront/rails/custom-css.mdxindex c7d8b4c718..fe2eca8d44 100644--- a/docs/developer/storefront/rails/custom-css.mdx+++ b/docs/v5/developer/storefront/rails/custom-css.mdx@@ -2,6 +2,7 @@title: "Custom CSS for Spree Storefront"sidebarTitle: "Custom CSS"description: "Add custom CSS to the Spree Rails Storefront by editing the Tailwind CSS application file, generating it when missing, and overriding theme styles."+canonical: "https://spreecommerce.org/docs/v5/developer/storefront/rails/custom-css"---Spree Storefront is built on top of [Tailwind CSS 4](https://tailwindcss.com/). After installing Spree you should find a main CSS file:@@ -265,6 +266,6 @@ Use them in your templates:## Related Documentation-- [Themes](/developer/storefront/rails/themes) - Theme settings and colors-- [Custom JavaScript](/developer/storefront/rails/custom-javascript) - Adding interactivity+- [Themes](/v5/developer/storefront/rails/themes) - Theme settings and colors+- [Custom JavaScript](/v5/developer/storefront/rails/custom-javascript) - Adding interactivity- [Tailwind CSS 4 Documentation](https://tailwindcss.com/docs) - Official Tailwind docsdiff --git a/docs/developer/storefront/rails/custom-javascript.mdx b/docs/v5/developer/storefront/rails/custom-javascript.mdxsimilarity index 94%rename from docs/developer/storefront/rails/custom-javascript.mdxrename to docs/v5/developer/storefront/rails/custom-javascript.mdxindex 7826f227c1..8eaf1520b7 100644--- a/docs/developer/storefront/rails/custom-javascript.mdx+++ b/docs/v5/developer/storefront/rails/custom-javascript.mdx@@ -2,6 +2,7 @@title: "Custom JavaScript for Spree Storefront"sidebarTitle: "Custom JavaScript"description: "Learn how to add custom JavaScript to your Spree storefront"+canonical: "https://spreecommerce.org/docs/v5/developer/storefront/rails/custom-javascript"---## Extending Storefront with JavaScript@@ -166,6 +167,6 @@ document.addEventListener('turbo:frame-load', (event) => {## Related Documentation-- [Custom CSS](/developer/storefront/rails/custom-css) - Styling your storefront-- [Sections](/developer/storefront/rails/sections) - Creating custom sections-- [Blocks](/developer/storefront/rails/blocks) - Creating custom blocks+- [Custom CSS](/v5/developer/storefront/rails/custom-css) - Styling your storefront+- [Sections](/v5/developer/storefront/rails/sections) - Creating custom sections+- [Blocks](/v5/developer/storefront/rails/blocks) - Creating custom blocksdiff --git a/docs/developer/storefront/rails/helper-methods.mdx b/docs/v5/developer/storefront/rails/helper-methods.mdxsimilarity index 94%rename from docs/developer/storefront/rails/helper-methods.mdxrename to docs/v5/developer/storefront/rails/helper-methods.mdxindex ef02567a83..61ed6d112b 100644--- a/docs/developer/storefront/rails/helper-methods.mdx+++ b/docs/v5/developer/storefront/rails/helper-methods.mdx@@ -1,6 +1,7 @@---title: Storefront Helper MethodssidebarTitle: Helper Methods+canonical: "https://spreecommerce.org/docs/v5/developer/storefront/rails/helper-methods"---import SpreeTheme from '/snippets/objects/spree_theme.mdx'@@ -270,7 +271,7 @@ Generates a URL for an image with specified dimensions.```<Info>- See [Media](/developer/core-concepts/media) for more details on image helpers.+ See [Media](/v5/developer/core-concepts/media) for more details on image helpers.</Info>## Product Helpers@@ -330,6 +331,6 @@ These helpers are used for Page Builder preview functionality:## Related Documentation-- [Sections](/developer/storefront/rails/sections) - Section rendering and customization-- [Blocks](/developer/storefront/rails/blocks) - Block rendering-- [Media](/developer/core-concepts/media) - Image helper methods+- [Sections](/v5/developer/storefront/rails/sections) - Section rendering and customization+- [Blocks](/v5/developer/storefront/rails/blocks) - Block rendering+- [Media](/v5/developer/core-concepts/media) - Image helper methodsdiff --git a/docs/developer/storefront/rails/links.mdx b/docs/v5/developer/storefront/rails/links.mdxsimilarity index 93%rename from docs/developer/storefront/rails/links.mdxrename to docs/v5/developer/storefront/rails/links.mdxindex 6fda64dfbd..0ab7e30d78 100644--- a/docs/developer/storefront/rails/links.mdx+++ b/docs/v5/developer/storefront/rails/links.mdx@@ -2,9 +2,10 @@title: "Links"sidebarTitle: "Links"description: "Learn how to use links for navigation in your Spree Storefront"+canonical: "https://spreecommerce.org/docs/v5/developer/storefront/rails/links"----Links are used to create navigation throughout the storefront. They can be assigned to [sections](/developer/storefront/rails/sections) and [blocks](/developer/storefront/rails/blocks), enabling users to navigate to different pages, products, categories, or external URLs.+Links are used to create navigation throughout the storefront. They can be assigned to [sections](/v5/developer/storefront/rails/sections) and [blocks](/v5/developer/storefront/rails/blocks), enabling users to navigate to different pages, products, categories, or external URLs.## How Links Work@@ -293,6 +294,6 @@ The label is derived from (in order):## Related Documentation-- [Sections](/developer/storefront/rails/sections) - Adding links to sections-- [Blocks](/developer/storefront/rails/blocks) - Adding links to blocks-- [Pages](/developer/storefront/rails/pages) - Understanding internal page linking+- [Sections](/v5/developer/storefront/rails/sections) - Adding links to sections+- [Blocks](/v5/developer/storefront/rails/blocks) - Adding links to blocks+- [Pages](/v5/developer/storefront/rails/pages) - Understanding internal page linkingdiff --git a/docs/developer/storefront/rails/pages.mdx b/docs/v5/developer/storefront/rails/pages.mdxsimilarity index 96%rename from docs/developer/storefront/rails/pages.mdxrename to docs/v5/developer/storefront/rails/pages.mdxindex 2a55e58f75..c603c09663 100644--- a/docs/developer/storefront/rails/pages.mdx+++ b/docs/v5/developer/storefront/rails/pages.mdx@@ -2,6 +2,7 @@title: "Storefront Pages"sidebarTitle: "Pages"description: "Learn how to create and use pages in your Spree Rails storefront"+canonical: "https://spreecommerce.org/docs/v5/developer/storefront/rails/pages"---## Built-in Pages@@ -29,7 +30,7 @@ We're planning to add page builder support for the following pages in the next S## Sections-Each page is made of [sections](/developer/storefront/rails/sections). Sections are the building blocks of a page. They are used to create the page content.+Each page is made of [sections](/v5/developer/storefront/rails/sections). Sections are the building blocks of a page. They are used to create the page content.You can fetch page sections using:diff --git a/docs/developer/storefront/rails/sections.mdx b/docs/v5/developer/storefront/rails/sections.mdxsimilarity index 99%rename from docs/developer/storefront/rails/sections.mdxrename to docs/v5/developer/storefront/rails/sections.mdxindex 8cfdbb4f9b..d81bcd2d90 100644--- a/docs/developer/storefront/rails/sections.mdx+++ b/docs/v5/developer/storefront/rails/sections.mdx@@ -1,6 +1,7 @@---title: "Sections"description: "Build Spree Rails Storefront pages with layout and content sections, including ActiveRecord models, theme views, and Page Builder admin forms."+canonical: "https://spreecommerce.org/docs/v5/developer/storefront/rails/sections"---## Quick Start@@ -116,7 +117,7 @@ You can access section's theme by calling `section.theme`.#### Preferences-Each section has set of default [preferences](/developer/customization/model-preferences)+Each section has set of default [preferences](/v5/developer/customization/model-preferences)| Name | Description | Default Value || --- | --- | --- |diff --git a/docs/developer/storefront/rails/storefront.mdx b/docs/v5/developer/storefront/rails/storefront.mdxsimilarity index 97%rename from docs/developer/storefront/rails/storefront.mdxrename to docs/v5/developer/storefront/rails/storefront.mdxindex d99d7711fd..086031c565 100644--- a/docs/developer/storefront/rails/storefront.mdx+++ b/docs/v5/developer/storefront/rails/storefront.mdx@@ -2,6 +2,7 @@title: "Rails Storefront Overview"sidebarTitle: "Overview"description: "Install and configure the Spree Rails Storefront, a mobile-first, themeable storefront built with Tailwind CSS, Turbo, Stimulus, and Importmaps."+canonical: "https://spreecommerce.org/docs/v5/developer/storefront/rails/storefront"---<Warning>diff --git a/docs/developer/storefront/rails/themes.mdx b/docs/v5/developer/storefront/rails/themes.mdxsimilarity index 96%rename from docs/developer/storefront/rails/themes.mdxrename to docs/v5/developer/storefront/rails/themes.mdxindex c33beb7ab9..3a77c6f669 100644--- a/docs/developer/storefront/rails/themes.mdx+++ b/docs/v5/developer/storefront/rails/themes.mdx@@ -2,6 +2,7 @@title: "Storefront Themes"sidebarTitle: "Themes"description: "Create and customize themes for the Spree Rails Storefront, including theme generators, template structure, and registering themes with the Page Builder."+canonical: "https://spreecommerce.org/docs/v5/developer/storefront/rails/themes"---<Warning>@@ -170,4 +171,4 @@ module Spreeend```-These are standard [Spree preferences](/developer/customization/model-preferences) that are configurable via Page Builder.+These are standard [Spree preferences](/v5/developer/customization/model-preferences) that are configurable via Page Builder.diff --git a/docs/developer/tutorial/admin.mdx b/docs/v5/developer/tutorial/admin.mdxsimilarity index 93%rename from docs/developer/tutorial/admin.mdxrename to docs/v5/developer/tutorial/admin.mdxindex 08efc01237..6a8c2e33a2 100644--- a/docs/developer/tutorial/admin.mdx+++ b/docs/v5/developer/tutorial/admin.mdx@@ -1,6 +1,7 @@---title: Admin Dashboarddescription: Scaffold the Spree admin UI for the Brands resource and add a rich text description editor, an Active Storage logo upload, and a custom table column.+canonical: "https://spreecommerce.org/docs/v5/developer/tutorial/admin"---<Note>@@ -49,7 +50,7 @@ You will now be able to access the brands resource at `http://localhost:3000/adm## Step 2: Add the Description Editor and Logo Upload-The generated form only knows about the `name` column. Let's add the rich text editor for `description` and the upload field for `logo` using Spree's [admin form builder](/developer/admin/form-builder):+The generated form only knows about the `name` column. Let's add the rich text editor for `description` and the upload field for `logo` using Spree's [admin form builder](/v5/developer/admin/form-builder):```erb app/views/spree/admin/brands/_form.html.erb {4,9-16}<div class="card mb-6">@@ -156,7 +157,7 @@ And create the partial:```<Info>-For complete table customization options including column types, filtering, sorting, and bulk actions, see the [Admin Tables](/developer/admin/tables) guide.+For complete table customization options including column types, filtering, sorting, and bulk actions, see the [Admin Tables](/v5/developer/admin/tables) guide.</Info>## Step 4: Customize Navigation@@ -206,9 +207,9 @@ endAfter restarting your server, you'll see the new "Brands" navigation link in the admin sidebar!<Info>-For complete navigation API documentation including all available options, submenu creation, badges, and more, see the [Admin Navigation](/developer/admin/navigation) guide. The form helpers used in Step 2 are documented in [Form Builder](/developer/admin/form-builder) and [Components](/developer/admin/components).+For complete navigation API documentation including all available options, submenu creation, badges, and more, see the [Admin Navigation](/v5/developer/admin/navigation) guide. The form helpers used in Step 2 are documented in [Form Builder](/v5/developer/admin/form-builder) and [Components](/v5/developer/admin/components).</Info>## Next Step-Brands are manageable in the admin. Now let's connect them to Products: [Extending Core Models](/developer/tutorial/extending-models).+Brands are manageable in the admin. Now let's connect them to Products: [Extending Core Models](/v5/developer/tutorial/extending-models).diff --git a/docs/developer/tutorial/api.mdx b/docs/v5/developer/tutorial/api.mdxsimilarity index 93%rename from docs/developer/tutorial/api.mdxrename to docs/v5/developer/tutorial/api.mdxindex 425c95ca80..9602978ccc 100644--- a/docs/developer/tutorial/api.mdx+++ b/docs/v5/developer/tutorial/api.mdx@@ -2,6 +2,7 @@title: Expose a custom model through the Store and Admin APIssidebarTitle: APIdescription: Expose your custom Brand model through the Spree Store and Admin REST APIs with serializers, controllers, routes, and the spree:api_resource generator.+canonical: "https://spreecommerce.org/docs/v5/developer/tutorial/api"---<Note>@@ -11,7 +12,7 @@ description: Expose your custom Brand model through the Spree Store and Admin REIn this tutorial, we'll expose our Brand model through Spree's v3 API — the customer-facing **Store API** that storefronts read from, and the back-office **Admin API** with full CRUD for apps and integrations. We'll also extend the existing Product serializer to include brand data.<Info>- This guide assumes you've completed the [Model](/developer/tutorial/model), [Admin](/developer/tutorial/admin), and [Extending Core Models](/developer/tutorial/extending-models) tutorials.+ This guide assumes you've completed the [Model](/v5/developer/tutorial/model), [Admin](/v5/developer/tutorial/admin), and [Extending Core Models](/v5/developer/tutorial/extending-models) tutorials.</Info>## What We're Building@@ -56,7 +57,7 @@ For a brand-new resource you'd pass the attributes too (`spree generate api_resoIf you just want a working API, run the generator and skip ahead to [Step 5: Test the Endpoints](#step-5-test-the-endpoints). The rest of this page builds the Store side by hand so you understand what the generator produces and how to customize it — the [Admin API section](#the-admin-api) then shows how little the back-office surface adds on top.<Tip>- Using an AI agent? The [Spree agent skills](/developer/agentic/agent-skills) include a dedicated resource-generator skill — your agent knows the field syntax, the flags, and the generated-file contract.+ Using an AI agent? The [Spree agent skills](/v5/developer/agentic/agent-skills) include a dedicated resource-generator skill — your agent knows the field syntax, the flags, and the generated-file contract.</Tip>## How the Store API Works@@ -72,7 +73,7 @@ Every Store API endpoint follows the same pattern:Store API requires two things from models:-1. **Prefixed IDs** — Stripe-style IDs like `brand_k5nR8xLq` instead of raw database IDs. The `spree:model` generator already added `has_prefix_id :brand` in the [Model step](/developer/tutorial/model), so this is done.+1. **Prefixed IDs** — Stripe-style IDs like `brand_k5nR8xLq` instead of raw database IDs. The `spree:model` generator already added `has_prefix_id :brand` in the [Model step](/v5/developer/tutorial/model), so this is done.2. **Slugs** — human-readable URL identifiers like `nike` for `GET /brands/nike`Add a `slug` column:@@ -378,7 +379,7 @@ curl -X POST -H "X-Spree-API-Key: sk_YOUR_KEY" \```<Info>- Secret keys carry scopes (`read_brands`, `write_brands` style) and JWT admin users go through CanCanCan abilities — see [API authentication](/developer/customization/api) for the full model. From TypeScript, the [Admin SDK](/developer/sdk/admin/quickstart) wraps the Admin API with typed clients for all built-in resources.+ Secret keys carry scopes (`read_brands`, `write_brands` style) and JWT admin users go through CanCanCan abilities — see [API authentication](/v5/developer/customization/api) for the full model. From TypeScript, the [Admin SDK](/v5/developer/sdk/admin/quickstart) wraps the Admin API with typed clients for all built-in resources.</Info>## Step 6: Add Brand to Product Responses@@ -617,8 +618,8 @@ Spree.ransack.add_association(Spree::Product, :brand)## Related Documentation-- [Extending Core Models](/developer/tutorial/extending-models) - Adding the Brand association to Product-- [Events & Webhooks](/developer/tutorial/events) - Lifecycle events for Brand and external-system integration (next step)-- [Using Brands with the SDK](/developer/tutorial/sdk) - Consuming brand endpoints from TypeScript-- [Decorators](/developer/customization/decorators) - Full decorator reference-- [Dependencies](/developer/customization/dependencies) - Swapping services and serializers+- [Extending Core Models](/v5/developer/tutorial/extending-models) - Adding the Brand association to Product+- [Events & Webhooks](/v5/developer/tutorial/events) - Lifecycle events for Brand and external-system integration (next step)+- [Using Brands with the SDK](/v5/developer/tutorial/sdk) - Consuming brand endpoints from TypeScript+- [Decorators](/v5/developer/customization/decorators) - Full decorator reference+- [Dependencies](/v5/developer/customization/dependencies) - Swapping services and serializersdiff --git a/docs/v5/developer/tutorial/events.mdx b/docs/v5/developer/tutorial/events.mdxnew file mode 100644index 0000000000..8497b23247--- /dev/null+++ b/docs/v5/developer/tutorial/events.mdx@@ -0,0 +1,173 @@+---+title: Events & Webhooks+description: React to Spree store activity and connect to external systems like an OMS, warehouse, or ERP using event subscribers, the subscriber generator, and webhooks.+canonical: "https://spreecommerce.org/docs/v5/developer/tutorial/events"+---++<Info>+ This guide assumes you've completed the [Model](/v5/developer/tutorial/model) and [API](/v5/developer/tutorial/api) tutorials — we'll reuse the Brand serializer created there.+</Info>++Almost every real store talks to other systems: an order management system (OMS), a warehouse (WMS), an ERP, a CRM, a marketing platform. In Spree, the integration surface is the **events system** — models publish events as things happen, and you react to them without touching core code.++There are two ways to consume events, and they serve different audiences:++| Mechanism | Code lives | Best for |+|---|---|---|+| **Subscriber** | In your Spree app | Calling external APIs with your own client code, internal side effects, anything needing app context |+| **Webhook** | In the external system | Letting a third party receive HTTP callbacks — no Ruby in your app, endpoints managed from the admin |++We'll do both: push completed orders to an OMS with a subscriber, give the Brand model its own lifecycle events, and set up an outbound webhook.++## Step 1: Subscribe to a Core Event++When an order completes, send it to the OMS. Generate a subscriber:++<CodeGroup>++```bash Spree CLI (Docker)+spree generate subscriber OmsOrderSync order.completed+```++```bash Without Spree CLI+bin/rails g spree:subscriber OmsOrderSync order.completed+```++</CodeGroup>++This creates the subscriber, a spec stub, and — crucially — **registers it** in `config/initializers/spree.rb` (injected into the existing `after_initialize` block every Spree app ships with). Subscribers are not auto-discovered; a subscriber that never gets appended to `Spree.subscribers` is a silent no-op, which is why the generator owns that step (re-runs are idempotent, and each new subscriber appends to the same initializer).++Fill in the handler:++```ruby app/subscribers/oms_order_sync_subscriber.rb+class OmsOrderSyncSubscriber < Spree::Subscriber+ subscribes_to 'order.completed'++ def handle(event)+ order = Spree::Order.find_by_prefix_id(event.payload['id'])+ return unless order++ OmsClient.create_order(+ number: order.number,+ email: order.email,+ line_items: order.line_items.map { |li| { sku: li.sku, quantity: li.quantity } }+ )+ end+end+```++Two things worth understanding:++- **Payloads carry prefixed IDs**, not raw database IDs — always look records up with `find_by_prefix_id`. The payload itself is the resource serialized with its v3 API serializer, so `event.payload['number']`, `['email']`, etc. are available directly when you don't need the full record.+- **Subscribers run async by default** — each `handle` call is an ActiveJob on the events queue, so a slow OMS API never blocks checkout. Pass `subscribes_to 'order.completed', async: false` only when you genuinely need synchronous execution.++Restart the server, complete a test order, and watch the job fire (`spree logs worker` — or your job backend's UI).++## Step 2: Give Brand Its Own Lifecycle Events++Core models like Payment and Shipment publish `*.created` / `*.updated` / `*.deleted` events automatically. Your models can too — add one line to the Brand model:++```ruby app/models/spree/brand.rb {3}+module Spree+ class Brand < Spree.base_class+ publishes_lifecycle_events++ # ... existing code ...+ end+end+```++Now `brand.created`, `brand.updated`, and `brand.deleted` fire after the matching transactions commit — and because you created `Spree::Api::V3::BrandSerializer` in the [API step](/v5/developer/tutorial/api), the payloads automatically use it (the events system resolves the serializer by naming convention). Anyone — subscriber or webhook — can react to brand changes with the same JSON shape your API serves.++<CodeGroup>++```bash Spree CLI (Docker)+spree generate subscriber BrandSync brand.created brand.updated+```++```bash Without Spree CLI+bin/rails g spree:subscriber BrandSync brand.created brand.updated+```++</CodeGroup>++```ruby app/subscribers/brand_sync_subscriber.rb+class BrandSyncSubscriber < Spree::Subscriber+ subscribes_to 'brand.created', 'brand.updated'++ def handle(event)+ SearchIndexer.upsert_brand(event.payload)+ end+end+```++## Step 3: Publish a Custom Event++Lifecycle events cover persistence; custom events express *domain* moments. Say featuring a brand should notify the marketing platform:++```ruby+brand.publish_event('brand.featured')+```++The payload defaults to the serializer output; pass your own hash as the second argument when the event needs different data. Subscribers consume it like any other event name.++## Step 4: Outbound Webhooks — No Code Required++When the consumer is an external system you don't deploy code into, use webhooks. In the admin, go to **Settings → Webhooks**, add an endpoint with the destination URL, and pick the events to deliver — `order.completed`, `brand.created`, anything publishing in your store. The endpoint's **signing secret is shown once on creation** — store it in the receiving system.++Each delivery is an HTTP POST with this envelope:++```json+{+ "id": "550e8400-e29b-41d4-a716-446655440000",+ "name": "order.completed",+ "created_at": "2026-06-11T12:00:00Z",+ "data": { "id": "or_m3Rp9wXz", "number": "R123456789", "...": "..." },+ "metadata": {}+}+```++And three headers the receiver should use:++| Header | Contents |+|---|---|+| `X-Spree-Webhook-Event` | The event name |+| `X-Spree-Webhook-Timestamp` | Unix timestamp of the delivery |+| `X-Spree-Webhook-Signature` | `HMAC-SHA256(secret, "{timestamp}.{body}")` |++Verify the signature before trusting a payload:++```ruby+def verified?(request, secret)+ timestamp = request.headers['X-Spree-Webhook-Timestamp']+ expected = OpenSSL::HMAC.hexdigest('SHA256', secret, "#{timestamp}.#{request.raw_post}")+ ActiveSupport::SecurityUtils.secure_compare(expected, request.headers['X-Spree-Webhook-Signature'])+end+```++Delivery semantics to design around: failed deliveries (timeouts, connection errors, non-2xx responses) are **recorded, not retried automatically** — redeliver from the endpoint's delivery history in the admin, or via `POST /api/v3/admin/webhook_endpoints/:webhook_endpoint_id/deliveries/:id/redeliver`. After **15 consecutive failures** the endpoint auto-disables and store staff get an email; a successful delivery resets the counter.++## Testing a Subscriber++Subscribers are plain Ruby — test `handle` directly with a constructed event:++```ruby spec/subscribers/oms_order_sync_subscriber_spec.rb+require 'rails_helper'++RSpec.describe OmsOrderSyncSubscriber do+ it 'pushes completed orders to the OMS' do+ order = create(:completed_order_with_totals)+ event = Spree::Event.new(name: 'order.completed', payload: { 'id' => order.prefixed_id })++ expect(OmsClient).to receive(:create_order).with(hash_including(number: order.number))++ described_class.new.handle(event)+ end+end+```++## Related Documentation++- [Events](/v5/developer/core-concepts/events) — the full event catalog, subscriber DSL, and delivery guarantees+- [Webhooks](/v5/developer/core-concepts/webhooks) — endpoint management, security, and the per-event payload schemas+- [Extending Core Models](/v5/developer/tutorial/extending-models) — when a decorator is the right tool insteaddiff --git a/docs/developer/tutorial/extending-models.mdx b/docs/v5/developer/tutorial/extending-models.mdxsimilarity index 85%rename from docs/developer/tutorial/extending-models.mdxrename to docs/v5/developer/tutorial/extending-models.mdxindex 8f8631d74a..f1da32e626 100644--- a/docs/developer/tutorial/extending-models.mdx+++ b/docs/v5/developer/tutorial/extending-models.mdx@@ -1,6 +1,7 @@---title: Extending Core Modelsdescription: Tutorial — extend Spree's core models with a custom Brand resource, generate a migration, and associate it with Products via a decorator.+canonical: "https://spreecommerce.org/docs/v5/developer/tutorial/extending-models"---<Note>@@ -10,7 +11,7 @@ description: Tutorial — extend Spree's core models with a custom Brand resourcIn this tutorial, we'll connect our custom Brand model with Spree's core Product model. This is a common pattern when building features that need to integrate with existing Spree functionality.<Info>- This guide assumes you've completed the [Model](/developer/tutorial/model) and [Admin](/developer/tutorial/admin) tutorials.+ This guide assumes you've completed the [Model](/v5/developer/tutorial/model) and [Admin](/v5/developer/tutorial/admin) tutorials.</Info>## What We're Building@@ -30,13 +31,13 @@ Before extending Spree models, consider which approach fits your needs best:| Add association (belongs_to, has_many) | **Decorator** (this tutorial) || Add validation or scope | **Decorator** || Add new instance/class method | **Decorator** |-| React to model changes (after save, etc.) | [Events subscriber](/developer/core-concepts/events) |-| Sync with external service on changes | [Events](/developer/core-concepts/events) or [Webhooks](/developer/core-concepts/webhooks) |-| Add searchable/filterable field | [Ransack configuration](/developer/core-concepts/search-filtering#extending-ransackable-configuration) |-| Add admin UI elements | [Admin Partials](/developer/admin/extending-ui) |+| React to model changes (after save, etc.) | [Events subscriber](/v5/developer/core-concepts/events) |+| Sync with external service on changes | [Events](/v5/developer/core-concepts/events) or [Webhooks](/v5/developer/core-concepts/webhooks) |+| Add searchable/filterable field | [Ransack configuration](/v5/developer/core-concepts/search-filtering#extending-ransackable-configuration) |+| Add admin UI elements | [Admin Partials](/v5/developer/admin/extending-ui) |<Info>- This tutorial uses **decorators** because we're adding a structural association between models. For behavioral changes like callbacks, prefer [Events](/developer/core-concepts/events) instead - they're easier to test and maintain.+ This tutorial uses **decorators** because we're adding a structural association between models. For behavioral changes like callbacks, prefer [Events](/v5/developer/core-concepts/events) instead - they're easier to test and maintain.</Info>## Understanding Decorators@@ -312,7 +313,7 @@ end#### Adding Callbacks<Warning>- For callbacks that trigger side effects (syncing to external services, sending notifications, etc.), use [Events subscribers](/developer/core-concepts/events) instead of decorator callbacks. Events are easier to test and won't break during Spree upgrades.+ For callbacks that trigger side effects (syncing to external services, sending notifications, etc.), use [Events subscribers](/v5/developer/core-concepts/events) instead of decorator callbacks. Events are easier to test and won't break during Spree upgrades.</Warning>**Decorator approach** (use only for simple, internal logic):@@ -327,7 +328,7 @@ def normalize_nameend```-**Events approach** (recommended for side effects): subscribe to `product.updated` and react in a `Spree::Subscriber` — no decorator, no callback coupling. The [Events & Webhooks tutorial](/developer/tutorial/events) builds this out fully, including external-system sync (OMS, warehouse) and outbound webhooks.+**Events approach** (recommended for side effects): subscribe to `product.updated` and react in a `Spree::Subscriber` — no decorator, no callback coupling. The [Events & Webhooks tutorial](/v5/developer/tutorial/events) builds this out fully, including external-system sync (OMS, warehouse) and outbound webhooks.#### Adding Class Methods@@ -375,7 +376,7 @@ end```<Info>- SEO features like slugs, meta titles, and FriendlyId are covered in the [Slugs](/developer/core-concepts/slugs) documentation.+ SEO features like slugs, meta titles, and FriendlyId are covered in the [Slugs](/v5/developer/core-concepts/slugs) documentation.</Info>### Spree Initializer Additions@@ -412,12 +413,12 @@ Now that Brands are connected to Products, let's expose them through the Store A## Related Documentation-- [Model Tutorial](/developer/tutorial/model) - Creating the Brand model-- [Admin Tutorial](/developer/tutorial/admin) - Building the admin interface-- [API Tutorial](/developer/tutorial/api) - Exposing brands through the API-- [Events & Webhooks tutorial](/developer/tutorial/events) - Subscribers, custom events, and webhooks in the Brand storyline-- [Events](/developer/core-concepts/events) - Subscribe to model changes without decorators-- [Webhooks](/developer/core-concepts/webhooks) - HTTP callbacks for external integrations-- [Decorators](/developer/customization/decorators) - Full decorator reference-- [Customization Overview](/developer/customization/quickstart) - More customization patterns-- [Products](/developer/core-concepts/products) - Product model documentation+- [Model Tutorial](/v5/developer/tutorial/model) - Creating the Brand model+- [Admin Tutorial](/v5/developer/tutorial/admin) - Building the admin interface+- [API Tutorial](/v5/developer/tutorial/api) - Exposing brands through the API+- [Events & Webhooks tutorial](/v5/developer/tutorial/events) - Subscribers, custom events, and webhooks in the Brand storyline+- [Events](/v5/developer/core-concepts/events) - Subscribe to model changes without decorators+- [Webhooks](/v5/developer/core-concepts/webhooks) - HTTP callbacks for external integrations+- [Decorators](/v5/developer/customization/decorators) - Full decorator reference+- [Customization Overview](/v5/developer/customization/quickstart) - More customization patterns+- [Products](/v5/developer/core-concepts/products) - Product model documentationdiff --git a/docs/v5/developer/tutorial/introduction.mdx b/docs/v5/developer/tutorial/introduction.mdxnew file mode 100644index 0000000000..d159401e5e--- /dev/null+++ b/docs/v5/developer/tutorial/introduction.mdx@@ -0,0 +1,64 @@+---+title: Tutorial+sidebarTitle: Introduction+description: Build a complete custom Brands feature in Spree — model, admin UI, Store and Admin APIs, events, and TypeScript storefront integration — end to end.+canonical: "https://spreecommerce.org/docs/v5/developer/tutorial/introduction"+---++This tutorial walks you through creating a complete Spree feature from scratch: a "Brands" feature that lets admins manage [Product](/v5/developer/core-concepts/products) brands, exposes them through the Store API, and consumes them from TypeScript.++It's written for **both backend and frontend developers**. The Ruby you'll write is minimal and mostly generated — Spree's generators produce convention-correct models, admin UIs, and API endpoints, and the TypeScript SDK gives you typed access from your storefront. You don't need to be a Rails expert to follow along.++## Before you start++You need a running Spree app. The fastest path is [create-spree-app](/v5/developer/create-spree-app/quickstart) — a Docker-based project with the [Spree CLI](/v5/developer/cli/quickstart), no local Ruby required:++```bash+npx create-spree-app@latest my-store+```++An existing app with Spree gems works just as well. **Every command in this tutorial is shown in two forms** — **Spree CLI** (runs inside Docker) and **Without Spree CLI** (runs directly on your machine) — pick the tab that matches your setup and ignore the other.++<Note>+ **create-spree-app projects:** run `spree eject` once before starting. Fresh projects use a prebuilt Docker image; ejecting switches to the dev setup that mounts `backend/` into the container, so the files the generators create land in your project (and reload live as you edit them).+</Note>++<Tip>+ Using an AI coding agent? Install the [Spree agent skills](/v5/developer/agentic/agent-skills) (`npx skills add spree/agent-skills`) and connect the [docs MCP server](/v5/developer/agentic/mcp) before starting — your agent will know the conventions this tutorial teaches and can follow along with you. See [Agentic Development](/v5/developer/agentic/overview).+</Tip>++## What you'll build++* A `Brand` model with a rich text description and an uploadable logo — one generator command+* An admin UI for managing brands — one generator command, then customized+* A `brand` association on Products, surfaced in the product admin form+* Store API endpoints (`GET /api/v3/store/brands`) with serializers and prefixed IDs+* Typed TypeScript access to brands from your storefront via `@spree/sdk`+* Event subscribers and webhooks connecting the store to external systems+* Automated tests for all of it++## Tutorial Sections++<CardGroup cols={2}>+ <Card title="1. Model" icon="database" href="/developer/tutorial/model">+ Generate the Brand model — columns, rich text description, and logo upload in one command+ </Card>+ <Card title="2. Admin Dashboard" icon="gauge" href="/developer/tutorial/admin">+ Scaffold the admin UI, then add the description editor, logo upload, and table columns+ </Card>+ <Card title="3. Extending Core Models" icon="plug" href="/developer/tutorial/extending-models">+ Connect Brands to Products using a decorator and an association+ </Card>+ <Card title="4. API" icon="code" href="/developer/tutorial/api">+ Expose Brands through the Store and Admin APIs — generated in one command, or hand-built to learn the pieces+ </Card>+ <Card title="5. Events & Webhooks" icon="zap" href="/developer/tutorial/events">+ React to store activity and connect external systems — OMS, warehouse, ERP+ </Card>+ <Card title="6. SDK" icon="js" href="/developer/tutorial/sdk">+ Consume Brand endpoints from TypeScript using the SDK+ </Card>+ <Card title="7. Testing" icon="flask-vial" href="/developer/tutorial/testing">+ Write automated tests for your feature+ </Card>+</CardGroup>diff --git a/docs/v5/developer/tutorial/model.mdx b/docs/v5/developer/tutorial/model.mdxnew file mode 100644index 0000000000..f09963ee36--- /dev/null+++ b/docs/v5/developer/tutorial/model.mdx@@ -0,0 +1,117 @@+---+title: Model+description: Create a custom Brand model in Spree with database columns, a rich text description, and an Active Storage logo upload using a single generator command.+canonical: "https://spreecommerce.org/docs/v5/developer/tutorial/model"+---++<Note>+ This is a backend customization. You need to perform it in the `backend` directory if you used `create-spree-app` to set up your Spree application.+</Note>++In this step we'll create the `Spree::Brand` model with everything it needs: a `name` column, a rich text `description`, and an uploadable `logo`.++## Step 1: Generate the Model++Spree ships a `spree:model` generator that produces a model and migration following all Spree conventions — `Spree::` namespacing, prefixed IDs, presence validations, and API filtering allowlists. It understands Rails attribute types including the virtual ones, so rich text and file attachments are part of the same command:++<CodeGroup>++```bash Spree CLI (Docker)+spree generate model Brand name:string:index description:rich_text logo:attachment+```++```bash Without Spree CLI+bin/rails g spree:model Brand name:string:index description:rich_text logo:attachment+```++</CodeGroup>++<Info>+ Throughout this tutorial every command is shown in two forms. **Spree CLI** is for projects created with [create-spree-app](/v5/developer/create-spree-app/quickstart), where the app runs in Docker and `spree <command>` routes into the container. **Without Spree CLI** is for apps running Spree backend directly on your machine.+</Info>++This creates two files:++- `app/models/spree/brand.rb` — the model+- `db/migrate/XXXXXXXXXXXXXX_create_spree_brands.rb` — the migration++Now apply the migration:++<CodeGroup>++```bash Spree CLI (Docker)+spree migrate+```++```bash Without Spree CLI+bin/rails db:migrate+```++</CodeGroup>++This creates the `spree_brands` table with an indexed `name` column. The `description` and `logo` attributes don't add columns — rich text lives in Action Text's `action_text_rich_texts` table, and uploads live in Active Storage's tables.++## Step 2: Understand the Generated Model++Open `app/models/spree/brand.rb`:++```ruby app/models/spree/brand.rb+module Spree+ class Brand < Spree.base_class+ has_prefix_id :brand++ has_rich_text :description+ has_one_attached :logo++ validates :name, presence: true++ self.whitelisted_ransackable_attributes = %w[name]+ self.whitelisted_ransackable_associations = %w[]+ self.whitelisted_ransackable_scopes = %w[]+ end+end+```++Line by line:++- **`Spree.base_class`** — inherits all Spree model functionality (multi-store scoping helpers, preferences, and more). The class is namespaced under `Spree::`, so it's available as `Spree::Brand`.+- **`has_prefix_id :brand`** — records get Stripe-style public IDs like `brand_k5nR8xLq`. APIs never expose raw database IDs.+- **`has_rich_text :description`** — formatted content via [Action Text](https://guides.rubyonrails.org/action_text_overview.html).+- **`has_one_attached :logo`** — file uploads via [Active Storage](https://guides.rubyonrails.org/active_storage_overview.html), with image processing and direct-to-storage uploads.+- **`validates :name, presence: true`** — generated automatically for required columns.+- **`whitelisted_ransackable_attributes`** — controls which attributes API clients may filter and sort by. Only allowlisted attributes are queryable, so adding `name` here is what later makes `?q[name_cont]=nike` work.++## Step 3: Try It in the Console++<CodeGroup>++```bash Spree CLI (Docker)+spree console+```++```bash Without Spree CLI+bin/rails console+```++</CodeGroup>++```ruby+brand = Spree::Brand.create!(name: "Wilson")+brand.prefixed_id # => "brand_k5nR8xLq"++brand.update!(description: "<h1>Hello</h1><p>World</p>")+brand.description.to_s # => rendered rich text HTML+brand.description.to_plain_text # => "Hello World"++Spree::Brand.find_by_prefix_id!("brand_k5nR8xLq") # lookup by public ID+```++We'll upload the logo through the admin UI in the next step — the model side is already done.++<Tip>+ The generator accepts more attribute types and options — references with auto-resolved class names (`user:belongs_to`), unique indexes (`slug:string:uniq`), soft delete (`--paranoid`), and custom fields support (`--metafields`). Run it with `--help` to see everything.+</Tip>++## Next Step++The model is complete. Now let's give admins a UI to manage brands: [Admin Dashboard](/v5/developer/tutorial/admin).diff --git a/docs/developer/tutorial/sdk.mdx b/docs/v5/developer/tutorial/sdk.mdxsimilarity index 85%rename from docs/developer/tutorial/sdk.mdxrename to docs/v5/developer/tutorial/sdk.mdxindex 3710ee2bf5..ec6ae13ad5 100644--- a/docs/developer/tutorial/sdk.mdx+++ b/docs/v5/developer/tutorial/sdk.mdx@@ -1,12 +1,13 @@---title: SDKdescription: Use the Spree TypeScript SDK to consume your custom Brand endpoints, fetch extended Product data, and surface the new resource in your headless storefront.+canonical: "https://spreecommerce.org/docs/v5/developer/tutorial/sdk"----In this tutorial, we'll use the `@spree/sdk` TypeScript SDK to consume the Brand API endpoints we created in the [API tutorial](/developer/tutorial/api), and work with the extended Product data that now includes brand information.+In this tutorial, we'll use the `@spree/sdk` TypeScript SDK to consume the Brand API endpoints we created in the [API tutorial](/v5/developer/tutorial/api), and work with the extended Product data that now includes brand information.<Info>- This guide assumes you've completed the [API](/developer/tutorial/api) tutorial and have the Brand endpoints running.+ This guide assumes you've completed the [API](/v5/developer/tutorial/api) tutorial and have the Brand endpoints running.</Info>## What We're Building@@ -117,7 +118,7 @@ const full = await client.products.get(### Filtering Products by Brand-Ransack predicates work on whitelisted attributes and associations. The [API tutorial](/developer/tutorial/api) shows how to register `brand_id` and `brand` via `Spree.ransack` — once that's done, you can filter:+Ransack predicates work on whitelisted attributes and associations. The [API tutorial](/v5/developer/tutorial/api) shows how to register `brand_id` and `brand` via `Spree.ransack` — once that's done, you can filter:```typescript// Products from a specific brand@@ -132,7 +133,7 @@ const nikeProducts2 = await client.products.list({```<Info>- Ransack predicates like `_eq`, `_cont`, `_gt`, `_lt` work on whitelisted attributes and associations. See [Search & Filtering](/developer/core-concepts/search-filtering) for the full list.+ Ransack predicates like `_eq`, `_cont`, `_gt`, `_lt` work on whitelisted attributes and associations. See [Search & Filtering](/v5/developer/core-concepts/search-filtering) for the full list.</Info>## Complete Example: Brand Page@@ -168,7 +169,7 @@ products.data.forEach(p => {## Related Documentation-- [API Tutorial](/developer/tutorial/api) - Creating the Brand API endpoints+- [API Tutorial](/v5/developer/tutorial/api) - Creating the Brand API endpoints- [SDK Overview](/sdk) - Full SDK documentation-- [Search & Filtering](/developer/core-concepts/search-filtering) - Ransack predicates and sorting-- [Agentic Development](/developer/agentic/overview) - Agent skills and the docs MCP server cover the SDK patterns used here+- [Search & Filtering](/v5/developer/core-concepts/search-filtering) - Ransack predicates and sorting+- [Agentic Development](/v5/developer/agentic/overview) - Agent skills and the docs MCP server cover the SDK patterns used herediff --git a/docs/v5/developer/tutorial/testing.mdx b/docs/v5/developer/tutorial/testing.mdxnew file mode 100644index 0000000000..acf3a517d0--- /dev/null+++ b/docs/v5/developer/tutorial/testing.mdx@@ -0,0 +1,730 @@+---+title: Testing+description: Write automated tests for the Brands tutorial feature using RSpec, Factory Bot, and Capybara, plus helpers from the spree_dev_tools gem.+canonical: "https://spreecommerce.org/docs/v5/developer/tutorial/testing"+---++Automated testing is a crucial part of the development process. It helps you ensure that your code works as expected and catches bugs early.+Spree uses [RSpec](https://rspec.info), [Factory Bot](https://github.com/thoughtbot/factory_bot_rails), and [Capybara](https://github.com/teamcapybara/capybara) for testing.+We also provide the `spree_dev_tools` gem that helps you write Spree-specific tests.++<Info>+ This guide assumes you've completed all previous tutorials through [API](/v5/developer/tutorial/api). You should have a complete `Spree::Brand` model with admin features and API endpoints.+</Info>++## Setup++**If your app came from [create-spree-app](/v5/developer/create-spree-app/quickstart) or [spree-starter](https://github.com/spree/spree-starter), the test environment is already set up** — RSpec, Factory Bot, Capybara, DatabaseCleaner, and the `spree_dev_tools` helpers (`stub_authorization!`, the `'API v3 Store'` shared context, Spree factories) ship preconfigured in `spec/support/`. Skip to creating the fixtures file below.++<Accordion title="Setting up an app that doesn't have RSpec yet">++For an existing Rails app without test setup, install RSpec and the Spree test helpers:++<CodeGroup>++```bash Spree CLI (Docker)+spree generate rspec:install+spree generate spree_dev_tools:install+```++```bash Without Spree CLI+bin/rails g rspec:install+bin/rails g spree_dev_tools:install+```++</CodeGroup>++The `spree_dev_tools` generator adds the Spree-specific helpers to `spec/support/`: authorization helpers (`stub_authorization!`), Factory Bot configuration, Capybara setup for feature tests, and more.++</Accordion>++### Create the Fixtures Directory and File++When writing tests that involve file attachments (like images, PDFs, etc.), you need fixture files that your factories can use. Here's how to set them up.++```bash+mkdir -p spec/fixtures/files && printf '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82' > spec/fixtures/files/logo.png+```++### What the generators already created++If you used `spree generate api_resource` in the [API step](/v5/developer/tutorial/api), you already have controller specs (`spec/controllers/spree/api/v3/store/brands_controller_spec.rb` and `…/admin/brands_controller_spec.rb`) and a factory (`spec/factories/spree/brand_factory.rb`). The sections below build the same things by hand — compare as you go, and keep whichever you prefer.++For the model spec, create `spec/models/spree/brand_spec.rb` — we'll fill it in below.++## Writing Factories++Factories provide a convenient way to create test data. Create a factory for your Brand model:++```ruby spec/factories/spree/brand_factory.rb+FactoryBot.define do+ factory :brand, class: Spree::Brand do+ sequence(:name) { |n| "Brand #{n}" }+ sequence(:slug) { |n| "brand-#{n}" }++ trait :with_description do+ description { '<div>A great brand for <strong>quality products</strong></div>' }+ end++ trait :with_logo do+ after(:create) do |brand|+ brand.logo.attach(+ io: File.new(Rails.root.join('spec', 'fixtures', 'files', 'logo.png')),+ filename: 'logo.png'+ )+ end+ end++ trait :with_products do+ transient do+ products_count { 3 }+ store { nil }+ end++ after(:create) do |brand, evaluator|+ store = evaluator.store || create(:store)+ create_list(:product, evaluator.products_count, brand: brand)+ end+ end+ end+end+```++### Factory Usage Examples++```ruby+# Basic factory+brand = create(:brand)++# With traits+brand = create(:brand, :with_description, :with_logo)++# With custom attributes+brand = create(:brand, name: 'Nike')++# Build without persisting (faster for unit tests)+brand = build(:brand)++# Create multiple records+brands = create_list(:brand, 5)++# With associated products+brand = create(:brand, :with_products)+brand = create(:brand, :with_products, products_count: 5)+```++## Writing Model Tests++Model tests verify your business logic, validations, associations, and scopes.++```ruby spec/models/spree/brand_spec.rb+require 'rails_helper'++RSpec.describe Spree::Brand, type: :model do+ describe 'associations' do+ it 'has many products' do+ association = described_class.reflect_on_association(:products)+ expect(association.macro).to eq(:has_many)+ expect(association.class_name).to eq('Spree::Product')+ end+ end++ describe 'validations' do+ it 'validates presence of name' do+ brand = build(:brand, name: nil)+ expect(brand).not_to be_valid+ expect(brand.errors[:name]).to include("can't be blank")+ end++ describe 'slug uniqueness' do+ let!(:existing_brand) { create(:brand, slug: 'nike') }++ it 'validates uniqueness of slug' do+ brand = build(:brand, slug: 'nike')+ expect(brand).not_to be_valid+ expect(brand.errors[:slug]).to include('has already been taken')+ end+ end+ end++ describe 'FriendlyId' do+ it 'generates slug from name' do+ brand = create(:brand, name: 'Nike Sportswear', slug: nil)+ expect(brand.slug).to eq('nike-sportswear')+ end++ it 'handles duplicate names by appending UUID' do+ create(:brand, name: 'Nike', slug: 'nike')+ brand = create(:brand, name: 'Nike', slug: nil)+ expect(brand.slug).to match(/nike-[a-f0-9-]+/)+ end+ end++ describe '#image' do+ let(:brand) { create(:brand, :with_logo) }++ it 'returns logo as image for Open Graph' do+ expect(brand.image).to eq(brand.logo)+ end+ end+end+```++### Testing Decorators++When you extend core Spree models with decorators (see [Extending Core Models](/v5/developer/tutorial/extending-models)), test the added functionality:++```ruby spec/models/spree/product_decorator_spec.rb+require 'rails_helper'++RSpec.describe 'Spree::Product brand association' do+ let(:store) { @default_store }+ let(:brand) { create(:brand) }+ let(:product) { create(:product) }++ describe 'brand association' do+ it 'can be assigned a brand' do+ product.brand = brand+ product.save!++ expect(product.reload.brand).to eq(brand)+ end++ it 'is optional' do+ product.brand = nil+ expect(product).to be_valid+ end+ end++ describe 'brand.products' do+ let!(:product1) { create(:product, brand: brand) }+ let!(:product2) { create(:product, brand: brand) }+ let!(:other_product) { create(:product) }++ it 'returns products for the brand' do+ expect(brand.products).to contain_exactly(product1, product2)+ end++ it 'nullifies brand_id when brand is destroyed' do+ brand.destroy+ expect(product1.reload.brand_id).to be_nil+ end+ end+end+```++## Writing Controller Tests++Controller tests verify that your endpoints respond correctly and perform the expected actions.++### Store API Controller Tests++Test the API endpoints we created in the [API tutorial](/v5/developer/tutorial/api). Store API tests use the `'API v3 Store'` shared context which sets up a store, publishable API key, and JWT tokens — it ships in the `spree_api` gem, so require `spree/api/testing_support/v3/base` at the top of the spec.++```ruby spec/controllers/spree/api/v3/store/brands_controller_spec.rb+require 'rails_helper'+require 'spree/api/testing_support/v3/base'++RSpec.describe Spree::Api::V3::Store::BrandsController, type: :controller do+ render_views++ include_context 'API v3 Store'++ let!(:brand1) { create(:brand, name: 'Nike') }+ let!(:brand2) { create(:brand, name: 'Adidas') }++ before do+ request.headers['X-Spree-Api-Key'] = api_key.token+ end++ describe 'GET #index' do+ it 'returns a list of brands' do+ get :index++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].size).to eq(2)+ end++ it 'returns brand attributes' do+ get :index++ brand_data = json_response['data'].first+ expect(brand_data).to include('id', 'name', 'slug')+ end++ it 'returns prefixed IDs' do+ get :index++ ids = json_response['data'].map { |b| b['id'] }+ ids.each { |id| expect(id).to start_with('brand_') }+ end++ it 'returns pagination metadata' do+ get :index, params: { page: 1, limit: 1 }++ expect(json_response['data'].size).to eq(1)+ expect(json_response['meta']).to include(+ 'page' => 1,+ 'limit' => 1,+ 'count' => 2,+ 'pages' => 2+ )+ end++ it 'filters by name' do+ get :index, params: { q: { name_cont: 'nik' } }++ expect(json_response['data'].size).to eq(1)+ expect(json_response['data'].first['name']).to eq('Nike')+ end++ it 'sorts by name' do+ get :index, params: { sort: 'name' }++ names = json_response['data'].map { |b| b['name'] }+ expect(names).to eq(%w[Adidas Nike])+ end+ end++ describe 'GET #show' do+ it 'returns a brand by prefixed ID' do+ get :show, params: { id: brand1.prefixed_id }++ expect(response).to have_http_status(:ok)+ expect(json_response['id']).to eq(brand1.prefixed_id)+ expect(json_response['name']).to eq('Nike')+ end++ it 'returns a brand by slug' do+ get :show, params: { id: brand1.slug }++ expect(response).to have_http_status(:ok)+ expect(json_response['name']).to eq('Nike')+ end++ it 'returns 404 for non-existent brand' do+ get :show, params: { id: 'brand_nonexistent' }++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'GET #show with logo' do+ let!(:brand_with_logo) { create(:brand, :with_logo) }++ it 'includes logo_url when logo is attached' do+ get :show, params: { id: brand_with_logo.prefixed_id }++ expect(json_response['logo_url']).to be_present+ end+ end+end+```++### Testing the Product Brand Association++Test that the custom Product serializer includes brand data:++```ruby spec/controllers/spree/api/v3/store/products_brand_spec.rb+require 'rails_helper'+require 'spree/api/testing_support/v3/base'++RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do+ render_views++ include_context 'API v3 Store'++ let(:brand) { create(:brand, name: 'Nike') }+ let!(:product) { create(:product, brand: brand, status: 'active') }++ before do+ request.headers['X-Spree-Api-Key'] = api_key.token+ end++ describe 'GET #show' do+ it 'includes brand_id' do+ get :show, params: { id: product.prefixed_id }++ expect(json_response['brand_id']).to eq(brand.prefixed_id)+ end++ it 'does not include brand object without expand' do+ get :show, params: { id: product.prefixed_id }++ expect(json_response).not_to have_key('brand')+ end++ it 'includes brand object with expand=brand' do+ get :show, params: { id: product.prefixed_id, expand: 'brand' }++ expect(json_response['brand']).to be_present+ expect(json_response['brand']['id']).to eq(brand.prefixed_id)+ expect(json_response['brand']['name']).to eq('Nike')+ end+ end++ describe 'GET #index' do+ it 'filters products by brand_id' do+ other_product = create(:product, status: 'active')++ get :index, params: { q: { brand_id_eq: brand.id } }++ ids = json_response['data'].map { |p| p['id'] }+ expect(ids).to include(product.prefixed_id)+ expect(ids).not_to include(other_product.prefixed_id)+ end+ end+end+```++### Admin Controller Tests++```ruby spec/controllers/spree/admin/brands_controller_spec.rb+require 'rails_helper'++RSpec.describe Spree::Admin::BrandsController, type: :controller do+ stub_authorization!+ render_views++ describe 'GET #index' do+ let!(:brand1) { create(:brand, name: 'Adidas') }+ let!(:brand2) { create(:brand, name: 'Nike') }++ it 'returns a successful response' do+ get :index+ expect(response).to be_successful+ end++ it 'displays all brands' do+ get :index+ expect(response.body).to include('Adidas')+ expect(response.body).to include('Nike')+ end+ end++ describe 'GET #new' do+ it 'returns a successful response' do+ get :new+ expect(response).to be_successful+ end++ it 'displays the new brand form' do+ get :new+ expect(response.body).to include('brand[name]')+ end+ end++ describe 'POST #create' do+ context 'with valid params' do+ let(:valid_params) do+ { brand: { name: 'New Brand' } }+ end++ it 'creates a new brand' do+ expect {+ post :create, params: valid_params+ }.to change(Spree::Brand, :count).by(1)+ end++ it 'redirects to the edit page' do+ post :create, params: valid_params+ expect(response).to redirect_to(spree.edit_admin_brand_path(Spree::Brand.last))+ end+ end++ context 'with invalid params' do+ let(:invalid_params) do+ { brand: { name: '' } }+ end++ it 'does not create a new brand' do+ expect {+ post :create, params: invalid_params+ }.not_to change(Spree::Brand, :count)+ end++ it 'returns unprocessable entity status' do+ post :create, params: invalid_params+ expect(response).to have_http_status(:unprocessable_content)+ end+ end+ end++ describe 'GET #edit' do+ let(:brand) { create(:brand) }++ it 'returns a successful response' do+ get :edit, params: { id: brand.id }+ expect(response).to be_successful+ end+ end++ describe 'PUT #update' do+ let(:brand) { create(:brand, name: 'Old Name') }++ context 'with valid params' do+ it 'updates the brand' do+ put :update, params: { id: brand.id, brand: { name: 'New Name' } }+ expect(brand.reload.name).to eq('New Name')+ end++ it 'redirects to the edit page' do+ put :update, params: { id: brand.id, brand: { name: 'New Name' } }+ expect(response).to redirect_to(spree.edit_admin_brand_path(brand))+ end+ end+ end++ describe 'DELETE #destroy' do+ let!(:brand) { create(:brand) }++ it 'removes the brand from the database' do+ expect {+ delete :destroy, params: { id: brand.id }, format: :html+ }.to change(Spree::Brand, :count).by(-1)+ end+ end+end+```++## Writing Feature Tests++Feature tests (also called system tests) simulate real user interactions using Capybara.++### Admin Feature Tests++```ruby spec/features/spree/admin/brands_spec.rb+require 'rails_helper'++RSpec.feature 'Admin Brands', type: :feature do+ stub_authorization!++ describe 'listing brands' do+ let!(:brand1) { create(:brand, name: 'Nike') }+ let!(:brand2) { create(:brand, name: 'Adidas') }++ it 'displays all brands' do+ visit spree.admin_brands_path++ expect(page).to have_content('Nike')+ expect(page).to have_content('Adidas')+ end+ end++ describe 'creating a brand' do+ it 'creates a new brand successfully' do+ visit spree.admin_brands_path+ click_on 'New Brand'++ fill_in 'Name', with: 'Puma'+ fill_in 'Slug', with: 'puma'++ click_on 'Create'+ wait_for_turbo++ expect(page).to have_content('Brand "Puma" has been successfully created!')+ expect(Spree::Brand.find_by(name: 'Puma')).to be_present+ end++ it 'shows validation errors' do+ visit spree.new_admin_brand_path++ click_on 'Create'+ wait_for_turbo++ expect(page).to have_content("can't be blank")+ end+ end++ describe 'editing a brand' do+ let!(:brand) { create(:brand, name: 'Nike') }++ it 'updates the brand successfully' do+ visit spree.admin_brands_path+ click_on 'Edit'++ fill_in 'Name', with: 'Nike Inc.'+ within('#page-header') { click_button 'Update' }++ wait_for_turbo+ expect(page).to have_content('Brand "Nike Inc." has been successfully updated!')+ expect(brand.reload.name).to eq('Nike Inc.')+ end+ end++ describe 'deleting a brand' do+ let!(:brand) { create(:brand, name: 'Nike') }++ it 'removes the brand' do+ expect {+ page.driver.submit :delete, spree.admin_brand_path(brand), {}+ }.to change(Spree::Brand, :count).by(-1)+ end+ end+end+```++## Test Helpers++### Authorization Helper++Use `stub_authorization!` to bypass authorization checks in admin tests:++```ruby+RSpec.describe Spree::Admin::BrandsController, type: :controller do+ stub_authorization! # Grants full admin access++ # ... your tests+end+```++### wait\_for\_turbo Helper++When testing with Turbo/Hotwire, use `wait_for_turbo` to ensure the page has fully loaded:++```ruby+click_on 'Create'+wait_for_turbo+expect(page).to have_content('Success!')+```++## Running Tests++### Prepare the test database++Tests run against a dedicated `spree_test` database, so your development data is never touched. Create it and load the schema once:++<CodeGroup>++```bash Spree CLI (Docker)+spree rails db:test:prepare+```++```bash Without Spree CLI+bin/rails db:test:prepare+```++</CodeGroup>++You rarely need to run this again — `rails_helper.rb` re-syncs the test schema automatically when you add migrations. It's the command to reach for when the test database gets into a broken or out-of-sync state.++### Run the suite++`spree rspec` runs `bundle exec rspec` inside the web container with `RAILS_ENV=test`. Everything after `rspec` is passed through, so file paths, line numbers, and flags work as usual:++<CodeGroup>++```bash Spree CLI (Docker)+spree rspec # all tests+spree rspec spec/models/spree/brand_spec.rb # specific file+spree rspec spec/models/spree/brand_spec.rb:15 # specific test+spree rspec --format documentation # documentation format+spree rspec spec/features/ # only feature tests+```++```bash Without Spree CLI+bundle exec rspec # all tests+bundle exec rspec spec/models/spree/brand_spec.rb # specific file+bundle exec rspec spec/models/spree/brand_spec.rb:15 # specific test+bundle exec rspec --format documentation # documentation format+bundle exec rspec spec/features/ # only feature tests+```++</CodeGroup>++<Accordion title="Troubleshooting: DatabaseCleaner refuses a remote database URL, or tests hit the development database">++Projects scaffolded before July 2026 set `DATABASE_URL` in `docker-compose.dev.yml`. A URL overrides `config/database.yml` for **every** Rails environment, so in-container tests pointed at the development database and tripped DatabaseCleaner's remote-URL safeguard. Two small changes bring an older project up to date:++1. In `docker-compose.dev.yml`, replace the `DATABASE_URL` entry under `environment:` with host/username parts, so each Rails environment resolves its own database from `database.yml`:++```yaml+ DATABASE_HOST: postgres+ DATABASE_USERNAME: postgres+```++2. In `spec/rails_helper.rb`, force the test environment — the dev container bakes in `RAILS_ENV=development`:++```ruby+ENV['RAILS_ENV'] = 'test'+```++Then restart the stack (`Ctrl+C` and `spree dev`) so the container picks up the new environment.++</Accordion>++## Best Practices++<CardGroup cols={2}>+ <Card title="Use build over create" icon="bolt">+ Use `build` instead of `create` when you don't need a persisted record. It's faster because it skips database operations.+ </Card>++ <Card title="Use let over instance variables" icon="code">+ Prefer `let` and `let!` over instance variables. They're lazily evaluated and scoped to each example.+ </Card>++ <Card title="One assertion per test" icon="check">+ Keep tests focused on a single behavior. Use `aggregate_failures` if you need multiple assertions.+ </Card>++ <Card title="Test behavior, not implementation" icon="eye">+ Focus on what the code does, not how it does it. This makes tests more resilient to refactoring.+ </Card>+</CardGroup>++### Example: aggregate\_failures++```ruby+it 'creates brand with all attributes', :aggregate_failures do+ brand = create(:brand, name: 'Nike')++ expect(brand.name).to eq('Nike')+ expect(brand.slug).to eq('nike')+end+```++## Complete Test Suite Structure++After completing this tutorial, your test structure should look like:++```+spec/+├── factories/+│ └── spree/+│ └── brand_factory.rb+├── models/+│ └── spree/+│ ├── brand_spec.rb+│ └── product_decorator_spec.rb+├── controllers/+│ └── spree/+│ ├── admin/+│ │ └── brands_controller_spec.rb+│ └── api/+│ └── v3/+│ └── store/+│ ├── brands_controller_spec.rb+│ └── products_brand_spec.rb+├── features/+│ └── spree/+│ └── admin/+│ └── brands_spec.rb+├── support/+│ └── (various support files)+├── rails_helper.rb+└── spec_helper.rb+```++## Related Documentation++* [Model Tutorial](/v5/developer/tutorial/model) - Creating the Brand model+* [Admin Tutorial](/v5/developer/tutorial/admin) - Building the admin interface+* [Extending Core Models](/v5/developer/tutorial/extending-models) - Connecting Brands to Products+* [API Tutorial](/v5/developer/tutorial/api) - Creating Brand API endpoints+* [Spree CLI](/v5/developer/cli/quickstart) - `spree rspec` and the other dev workflow commands+* [RSpec Documentation](https://rspec.info/documentation/) - Official RSpec docs+* [Factory Bot Documentation](https://github.com/thoughtbot/factory_bot/blob/main/GETTING_STARTED.md) - Factory Bot guide+++---diff --git a/docs/developer/upgrades/2.0-to-2.1.mdx b/docs/v5/developer/upgrades/2.0-to-2.1.mdxsimilarity index 93%rename from docs/developer/upgrades/2.0-to-2.1.mdxrename to docs/v5/developer/upgrades/2.0-to-2.1.mdxindex 8664b5768d..ad36e3771b 100644--- a/docs/developer/upgrades/2.0-to-2.1.mdx+++ b/docs/v5/developer/upgrades/2.0-to-2.1.mdx@@ -1,6 +1,7 @@---title: 2.0 to 2.1description: 'This guide covers upgrading a 2.0 Spree store, to a 2.1 store.'+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/2.0-to-2.1"---## Overviewdiff --git a/docs/developer/upgrades/2.1-to-2.2.mdx b/docs/v5/developer/upgrades/2.1-to-2.2.mdxsimilarity index 95%rename from docs/developer/upgrades/2.1-to-2.2.mdxrename to docs/v5/developer/upgrades/2.1-to-2.2.mdxindex 8481ef0c14..6c3c65c2cb 100644--- a/docs/developer/upgrades/2.1-to-2.2.mdx+++ b/docs/v5/developer/upgrades/2.1-to-2.2.mdx@@ -2,6 +2,7 @@title: 2.1 to 2.2section: upgradesdescription: 'This guide covers upgrading a 2.1 Spree store, to a 2.2 store.'+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/2.1-to-2.2"---diff --git a/docs/developer/upgrades/2.2-to-2.3.mdx b/docs/v5/developer/upgrades/2.2-to-2.3.mdxsimilarity index 93%rename from docs/developer/upgrades/2.2-to-2.3.mdxrename to docs/v5/developer/upgrades/2.2-to-2.3.mdxindex 8a1fbbb0f7..b781f00315 100644--- a/docs/developer/upgrades/2.2-to-2.3.mdx+++ b/docs/v5/developer/upgrades/2.2-to-2.3.mdx@@ -1,6 +1,7 @@---title: 2.2 to 2.3description: 'This guide covers upgrading a 2.2 Spree store, to a 2.3 store.'+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/2.2-to-2.3"---## Overviewdiff --git a/docs/developer/upgrades/2.3-to-2.4.mdx b/docs/v5/developer/upgrades/2.3-to-2.4.mdxsimilarity index 93%rename from docs/developer/upgrades/2.3-to-2.4.mdxrename to docs/v5/developer/upgrades/2.3-to-2.4.mdxindex 4688a3d8c4..8f24fe315f 100644--- a/docs/developer/upgrades/2.3-to-2.4.mdx+++ b/docs/v5/developer/upgrades/2.3-to-2.4.mdx@@ -2,6 +2,7 @@title: 2.3 to 2.4section: upgradesdescription: 'This guide covers upgrading a 2.3 Spree store, to a 2.4 store.'+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/2.3-to-2.4"---This guide has been written from the perspective of a blank Spree 2.3 store with no extensions.diff --git a/docs/developer/upgrades/3.0-to-3.1.mdx b/docs/v5/developer/upgrades/3.0-to-3.1.mdxsimilarity index 93%rename from docs/developer/upgrades/3.0-to-3.1.mdxrename to docs/v5/developer/upgrades/3.0-to-3.1.mdxindex 8e3b1b37bb..c66be01225 100644--- a/docs/developer/upgrades/3.0-to-3.1.mdx+++ b/docs/v5/developer/upgrades/3.0-to-3.1.mdx@@ -3,6 +3,7 @@ title: 3.0 to 3.1section: upgradesorder: 9description: 'This guide covers upgrading a 3.0 Spree store, to a 3.1 store'+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/3.0-to-3.1"---## Update gemsdiff --git a/docs/developer/upgrades/3.1-to-3.2.mdx b/docs/v5/developer/upgrades/3.1-to-3.2.mdxsimilarity index 90%rename from docs/developer/upgrades/3.1-to-3.2.mdxrename to docs/v5/developer/upgrades/3.1-to-3.2.mdxindex b1ef9971c7..a745c07629 100644--- a/docs/developer/upgrades/3.1-to-3.2.mdx+++ b/docs/v5/developer/upgrades/3.1-to-3.2.mdx@@ -3,6 +3,7 @@ title: 3.1 to 3.2section: upgradesorder: 8description: 'This guide covers upgrading a 3.1 Spree store, to a 3.2 store.'+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/3.1-to-3.2"---### Update your Rails version to 5.0diff --git a/docs/developer/upgrades/3.2-to-3.3.mdx b/docs/v5/developer/upgrades/3.2-to-3.3.mdxsimilarity index 96%rename from docs/developer/upgrades/3.2-to-3.3.mdxrename to docs/v5/developer/upgrades/3.2-to-3.3.mdxindex 033bf66eda..134087dc66 100644--- a/docs/developer/upgrades/3.2-to-3.3.mdx+++ b/docs/v5/developer/upgrades/3.2-to-3.3.mdx@@ -3,6 +3,7 @@ title: 3.2 to 3.3section: upgradesorder: 7description: 'This guide covers upgrading a 3.2 Spree store, to a 3.3 store.'+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/3.2-to-3.3"---### Update your Rails version to 5.1diff --git a/docs/developer/upgrades/3.3-to-3.4.mdx b/docs/v5/developer/upgrades/3.3-to-3.4.mdxsimilarity index 90%rename from docs/developer/upgrades/3.3-to-3.4.mdxrename to docs/v5/developer/upgrades/3.3-to-3.4.mdxindex 538e0d02fa..e338778c07 100644--- a/docs/developer/upgrades/3.3-to-3.4.mdx+++ b/docs/v5/developer/upgrades/3.3-to-3.4.mdx@@ -3,6 +3,7 @@ title: 3.3 to 3.4section: upgradesorder: 6description: 'This guide covers upgrading a 3.3 Spree store, to a 3.4 store.'+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/3.3-to-3.4"---### Update gemsdiff --git a/docs/developer/upgrades/3.4-to-3.5.mdx b/docs/v5/developer/upgrades/3.4-to-3.5.mdxsimilarity index 92%rename from docs/developer/upgrades/3.4-to-3.5.mdxrename to docs/v5/developer/upgrades/3.4-to-3.5.mdxindex 3c75f78ef4..757e40247e 100644--- a/docs/developer/upgrades/3.4-to-3.5.mdx+++ b/docs/v5/developer/upgrades/3.4-to-3.5.mdx@@ -3,6 +3,7 @@ title: 3.4 to 3.5section: upgradesorder: 5description: 'This guide covers upgrading a 3.4 Spree store, to a 3.5 store.'+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/3.4-to-3.5"---### Update gemsdiff --git a/docs/developer/upgrades/3.5-to-3.6.mdx b/docs/v5/developer/upgrades/3.5-to-3.6.mdxsimilarity index 93%rename from docs/developer/upgrades/3.5-to-3.6.mdxrename to docs/v5/developer/upgrades/3.5-to-3.6.mdxindex fb53ca9b6f..5b3cd931c0 100644--- a/docs/developer/upgrades/3.5-to-3.6.mdx+++ b/docs/v5/developer/upgrades/3.5-to-3.6.mdx@@ -3,6 +3,7 @@ title: 3.5 to 3.6section: upgradesorder: 4description: 'This guide covers upgrading a 3.5 Spree application, to a 3.6 application.'+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/3.5-to-3.6"---## Update your Rails version to 5.2diff --git a/docs/developer/upgrades/3.6-to-3.7.mdx b/docs/v5/developer/upgrades/3.6-to-3.7.mdxsimilarity index 95%rename from docs/developer/upgrades/3.6-to-3.7.mdxrename to docs/v5/developer/upgrades/3.6-to-3.7.mdxindex ded9fa9124..9a8fadac83 100644--- a/docs/developer/upgrades/3.6-to-3.7.mdx+++ b/docs/v5/developer/upgrades/3.6-to-3.7.mdx@@ -3,6 +3,7 @@ title: 3.6 to 3.7section: upgradesorder: 3description: 'This guide covers upgrading a 3.6 Spree application, to version 3.7.'+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/3.6-to-3.7"---## Update gemsdiff --git a/docs/developer/upgrades/3.7-to-4.0.mdx b/docs/v5/developer/upgrades/3.7-to-4.0.mdxsimilarity index 97%rename from docs/developer/upgrades/3.7-to-4.0.mdxrename to docs/v5/developer/upgrades/3.7-to-4.0.mdxindex e42b8decf9..9989741981 100644--- a/docs/developer/upgrades/3.7-to-4.0.mdx+++ b/docs/v5/developer/upgrades/3.7-to-4.0.mdx@@ -3,6 +3,7 @@ title: 3.7 to 4.0section: upgradesorder: 2description: This guide covers upgrading a 3.7 Spree application to Spree 4.0.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/3.7-to-4.0"---diff --git a/docs/developer/upgrades/4.0-to-4.1.mdx b/docs/v5/developer/upgrades/4.0-to-4.1.mdxsimilarity index 97%rename from docs/developer/upgrades/4.0-to-4.1.mdxrename to docs/v5/developer/upgrades/4.0-to-4.1.mdxindex 5940415218..5ca4110c22 100644--- a/docs/developer/upgrades/4.0-to-4.1.mdx+++ b/docs/v5/developer/upgrades/4.0-to-4.1.mdx@@ -3,6 +3,7 @@ title: 4.0 to 4.1section: upgradesorder: 1description: This guide covers upgrading a 4.0 Spree application to Spree 4.1.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/4.0-to-4.1"---<Note>diff --git a/docs/developer/upgrades/4.1-to-4.2.mdx b/docs/v5/developer/upgrades/4.1-to-4.2.mdxsimilarity index 98%rename from docs/developer/upgrades/4.1-to-4.2.mdxrename to docs/v5/developer/upgrades/4.1-to-4.2.mdxindex 66350ced54..9f7e2913a8 100644--- a/docs/developer/upgrades/4.1-to-4.2.mdx+++ b/docs/v5/developer/upgrades/4.1-to-4.2.mdx@@ -3,6 +3,7 @@ title: 4.1 to 4.2section: upgradesorder: 0description: This guide covers upgrading a 4.1 Spree application to Spree 4.2.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/4.1-to-4.2"---diff --git a/docs/developer/upgrades/4.10-to-5.0.mdx b/docs/v5/developer/upgrades/4.10-to-5.0.mdxsimilarity index 85%rename from docs/developer/upgrades/4.10-to-5.0.mdxrename to docs/v5/developer/upgrades/4.10-to-5.0.mdxindex 7e077698e3..ac5bd75ff5 100644--- a/docs/developer/upgrades/4.10-to-5.0.mdx+++ b/docs/v5/developer/upgrades/4.10-to-5.0.mdx@@ -1,10 +1,11 @@---title: Upgrading to Spree 5.0description: This guide covers upgrading a Spree 4.10 application to Spree 5.0.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/4.10-to-5.0"---<Info>- Before proceeding to upgrade, please ensure you're at [Spree 4.10](/developer/upgrades/4.9-to-4.10)+ Before proceeding to upgrade, please ensure you're at [Spree 4.10](/v5/developer/upgrades/4.9-to-4.10)</Info>Spree 5.0 is a major upgrade that introduces many breaking changes. The major changes are:@@ -13,9 +14,9 @@ Spree 5.0 is a major upgrade that introduces many breaking changes. The major ch- Dropped support for Spree Auth Devise gem (now using Devise gem directly via generator, you're in more control of the authentication now)- Completely new Admin Dashboard (old customizations unfortunately won't work)- Completely new native Stripe extension-- [Spree 5.1](https://github.com/spree/spree/releases/tag/v5.1.0) includes native [Gift Cards](/developer/core-concepts/store-credits-gift-cards), Admin Staff Management & Invitations-- [Spree 5.2](https://github.com/spree/spree/releases/tag/v5.2.0) includes [Metafields](/developer/core-concepts/metafields), CSV Importer, Store Policies & Newsletter Subscribers-- [Spree 5.3](https://github.com/spree/spree/releases/tag/v5.3.0) includes new highly flexible [Pricing Engine](/user/manage-products/price-lists) for B2B, Wholesale and Volume discounts, [Events & Subscribers Engine](/developer/core-concepts/events), [Webhooks](/developer/core-concepts/webhooks), [Customer Groups](/user/customers/customer-groups)+- [Spree 5.1](https://github.com/spree/spree/releases/tag/v5.1.0) includes native [Gift Cards](/v5/developer/core-concepts/store-credits-gift-cards), Admin Staff Management & Invitations+- [Spree 5.2](https://github.com/spree/spree/releases/tag/v5.2.0) includes [Metafields](/v5/developer/core-concepts/metafields), CSV Importer, Store Policies & Newsletter Subscribers+- [Spree 5.3](https://github.com/spree/spree/releases/tag/v5.3.0) includes new highly flexible [Pricing Engine](/v5/user/manage-products/price-lists) for B2B, Wholesale and Volume discounts, [Events & Subscribers Engine](/v5/developer/core-concepts/events), [Webhooks](/v5/developer/core-concepts/webhooks), [Customer Groups](/v5/user/customers/customer-groups)- [Spree 5.4](https://github.com/spree/spree/releases/tag/v5.4.0) includes new [API v3](/api-reference/store-api) and [Next.js Storefront](https://github.com/spree/storefront)## Prerequisitesdiff --git a/docs/developer/upgrades/4.2-to-4.3.mdx b/docs/v5/developer/upgrades/4.2-to-4.3.mdxsimilarity index 97%rename from docs/developer/upgrades/4.2-to-4.3.mdxrename to docs/v5/developer/upgrades/4.2-to-4.3.mdxindex 2e9f7d05da..4f8d025a99 100644--- a/docs/developer/upgrades/4.2-to-4.3.mdx+++ b/docs/v5/developer/upgrades/4.2-to-4.3.mdx@@ -4,6 +4,7 @@ section: upgradesorder: 0hidden: truedescription: Upgrade a Spree 4.2 application to Spree 4.3 — split out spree_emails, spree_backend, and spree_frontend gems, remove merged extensions, and run migrations.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/4.2-to-4.3"---<Note>diff --git a/docs/developer/upgrades/4.3-to-4.4.mdx b/docs/v5/developer/upgrades/4.3-to-4.4.mdxsimilarity index 97%rename from docs/developer/upgrades/4.3-to-4.4.mdxrename to docs/v5/developer/upgrades/4.3-to-4.4.mdxindex 8b5b586f87..c75ba8f14b 100644--- a/docs/developer/upgrades/4.3-to-4.4.mdx+++ b/docs/v5/developer/upgrades/4.3-to-4.4.mdx@@ -1,6 +1,7 @@---title: 4.3 to 4.4description: This guide covers upgrading a 4.3 Spree application to Spree 4.4.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/4.3-to-4.4"---<Note>diff --git a/docs/developer/upgrades/4.4-to-4.5.mdx b/docs/v5/developer/upgrades/4.4-to-4.5.mdxsimilarity index 97%rename from docs/developer/upgrades/4.4-to-4.5.mdxrename to docs/v5/developer/upgrades/4.4-to-4.5.mdxindex 2382626699..8652f9bf96 100644--- a/docs/developer/upgrades/4.4-to-4.5.mdx+++ b/docs/v5/developer/upgrades/4.4-to-4.5.mdx@@ -1,6 +1,7 @@---title: 4.4 to 4.5description: This guide covers upgrading a 4.4 Spree application to Spree 4.5+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/4.4-to-4.5"---<Warning>diff --git a/docs/developer/upgrades/4.5-to-4.6.mdx b/docs/v5/developer/upgrades/4.5-to-4.6.mdxsimilarity index 86%rename from docs/developer/upgrades/4.5-to-4.6.mdxrename to docs/v5/developer/upgrades/4.5-to-4.6.mdxindex 1d1c737471..5dca7c36bd 100644--- a/docs/developer/upgrades/4.5-to-4.6.mdx+++ b/docs/v5/developer/upgrades/4.5-to-4.6.mdx@@ -1,6 +1,7 @@---title: 4.5 to 4.6description: This guide covers upgrading a 4.5 Spree application to Spree 4.6.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/4.5-to-4.6"---<Warning>@@ -30,7 +31,7 @@ If your application used the spree_globalize extension, you can remove it from yWe've configured Mobility to use [a strategy that uses a separate table to store translations](https://dejimata.com/2017/3/3/translating-with-mobility#strategy-2), just like how spree_globalize did. This means, you won't need to make any changes to the database structure or migrate data.-During the upgrade process, you may need to review your custom queries that rely on translations, as there are minor differences in how Mobility handles them. Spree 4.6 includes a few [built-in concerns](/developer/core-concepts/translations#resource-translations-implementation) to make it easier to work with translatable models.+During the upgrade process, you may need to review your custom queries that rely on translations, as there are minor differences in how Mobility handles them. Spree 4.6 includes a few [built-in concerns](/v5/developer/core-concepts/translations#resource-translations-implementation) to make it easier to work with translatable models.Run the following command to remove spree_globalize from your Gemfile:@@ -74,7 +75,7 @@ bin/rails g spree:frontend:install### Update migrations for translation tables with additional columns-If you want to translate more fields in [translated resources](/developer/core-concepts/translations#resource-translations), you have to alter copied migrations or add new ones.+If you want to translate more fields in [translated resources](/v5/developer/core-concepts/translations#resource-translations), you have to alter copied migrations or add new ones.We're using the [Spree::TranslationMigrations](https://github.com/spree/spree/blob/main/core/lib/spree/translation_migrations.rb) to help with migrating data.### Add or update the behavior of the translated model@@ -86,7 +87,7 @@ If you overwrote Spree models in your application, you have to define this block- `Spree::TranslatableResource` - required for all translated models- `Spree::TranslatableResourceSlug` - required for translated models with slugs/permalinks-[Read more](/developer/core-concepts/translations#resource-translations-implementation) how Spree handles resource translations.+[Read more](/v5/developer/core-concepts/translations#resource-translations-implementation) how Spree handles resource translations.### Generating slugs with `friendly_id`@@ -98,7 +99,7 @@ Currently, it's not possible to translate encrypted data. If you're already encr### Full text search with pg_search scopes-If you use the [pg_search](https://github.com/Casecommons/pg_search) for the full text search in [translated resources](/developer/core-concepts/translations#resource-translations), you need to move your scopes to the translated model, eg. from the `Spree::Product` to the `Spree::Product::Translation`.+If you use the [pg_search](https://github.com/Casecommons/pg_search) for the full text search in [translated resources](/v5/developer/core-concepts/translations#resource-translations), you need to move your scopes to the translated model, eg. from the `Spree::Product` to the `Spree::Product::Translation`.If you still want to have the original scope, you need to rewrite it, from:diff --git a/docs/developer/upgrades/4.6-to-4.7.mdx b/docs/v5/developer/upgrades/4.6-to-4.7.mdxsimilarity index 94%rename from docs/developer/upgrades/4.6-to-4.7.mdxrename to docs/v5/developer/upgrades/4.6-to-4.7.mdxindex 7472418768..63e6b20e48 100644--- a/docs/developer/upgrades/4.6-to-4.7.mdx+++ b/docs/v5/developer/upgrades/4.6-to-4.7.mdx@@ -1,6 +1,7 @@---title: 4.6 to 4.7description: This guide covers upgrading a 4.6 Spree application to Spree 4.7.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/4.6-to-4.7"---<Warning>diff --git a/docs/developer/upgrades/4.8-to-4.9.mdx b/docs/v5/developer/upgrades/4.8-to-4.9.mdxsimilarity index 82%rename from docs/developer/upgrades/4.8-to-4.9.mdxrename to docs/v5/developer/upgrades/4.8-to-4.9.mdxindex 608e7874f6..7ee707e8cd 100644--- a/docs/developer/upgrades/4.8-to-4.9.mdx+++ b/docs/v5/developer/upgrades/4.8-to-4.9.mdx@@ -1,10 +1,11 @@---title: Upgrading to Spree 4.9description: This guide covers upgrading a Spree 4.8 application to Spree 4.9.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/4.8-to-4.9"---<Info>- Before proceeding to upgrade, please ensure you're at [Spree 4.8](/developer/upgrades/4.x-to-4.8)+ Before proceeding to upgrade, please ensure you're at [Spree 4.8](/v5/developer/upgrades/4.x-to-4.8)</Info>## Upgrade stepsdiff --git a/docs/developer/upgrades/4.9-to-4.10.mdx b/docs/v5/developer/upgrades/4.9-to-4.10.mdxsimilarity index 82%rename from docs/developer/upgrades/4.9-to-4.10.mdxrename to docs/v5/developer/upgrades/4.9-to-4.10.mdxindex ffe6ecde1d..e632a89a9a 100644--- a/docs/developer/upgrades/4.9-to-4.10.mdx+++ b/docs/v5/developer/upgrades/4.9-to-4.10.mdx@@ -1,10 +1,11 @@---title: Upgrading to Spree 4.10description: This guide covers upgrading a Spree 4.9 application to Spree 4.10.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/4.9-to-4.10"---<Info>- Before proceeding to upgrade, please ensure you're at [Spree 4.9](/developer/upgrades/4.8-to-4.9)+ Before proceeding to upgrade, please ensure you're at [Spree 4.9](/v5/developer/upgrades/4.8-to-4.9)</Info>## Upgrade stepsdiff --git a/docs/developer/upgrades/4.x-to-4.8.mdx b/docs/v5/developer/upgrades/4.x-to-4.8.mdxsimilarity index 94%rename from docs/developer/upgrades/4.x-to-4.8.mdxrename to docs/v5/developer/upgrades/4.x-to-4.8.mdxindex 0c31f5e37c..35d92a8993 100644--- a/docs/developer/upgrades/4.x-to-4.8.mdx+++ b/docs/v5/developer/upgrades/4.x-to-4.8.mdx@@ -1,6 +1,7 @@---title: Upgrading to Spree 4.8description: This guide covers upgrading a Spree 4 application to Spree 4.8.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/4.x-to-4.8"---<Info>diff --git a/docs/developer/upgrades/5.0-to-5.1.mdx b/docs/v5/developer/upgrades/5.0-to-5.1.mdxsimilarity index 85%rename from docs/developer/upgrades/5.0-to-5.1.mdxrename to docs/v5/developer/upgrades/5.0-to-5.1.mdxindex 8db03a8838..8952d87f29 100644--- a/docs/developer/upgrades/5.0-to-5.1.mdx+++ b/docs/v5/developer/upgrades/5.0-to-5.1.mdx@@ -1,10 +1,11 @@---title: Upgrading to Spree 5.1description: This guide covers upgrading a Spree 5.0 application to Spree 5.1.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/5.0-to-5.1"---<Info>- Before proceeding to upgrade, please ensure you're at [Spree 5.0](/developer/upgrades/4.10-to-5.0)+ Before proceeding to upgrade, please ensure you're at [Spree 5.0](/v5/developer/upgrades/4.10-to-5.0)</Info>## Upgrade stepsdiff --git a/docs/developer/upgrades/5.1-to-5.2.mdx b/docs/v5/developer/upgrades/5.1-to-5.2.mdxsimilarity index 91%rename from docs/developer/upgrades/5.1-to-5.2.mdxrename to docs/v5/developer/upgrades/5.1-to-5.2.mdxindex fba431b942..7057cc9911 100644--- a/docs/developer/upgrades/5.1-to-5.2.mdx+++ b/docs/v5/developer/upgrades/5.1-to-5.2.mdx@@ -1,10 +1,11 @@---title: Upgrading to Spree 5.2description: This guide covers upgrading a Spree 5.1 application to Spree 5.2.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/5.1-to-5.2"---<Info>- Before proceeding to upgrade, please ensure you're at [Spree 5.1](/developer/upgrades/5.0-to-5.1)+ Before proceeding to upgrade, please ensure you're at [Spree 5.1](/v5/developer/upgrades/5.0-to-5.1)</Info>## Upgrade steps@@ -35,7 +36,7 @@ bin/rake spree:install:migrations && bin/rails db:migrate### Migrate to Metafields or keep using Product Properties-Spree 5.2 introduces [Metafields](/developer/core-concepts/metafields), which are a new way to store additional information about an object. Previously, we used Product Properties to enrich products. Metafields are more powerful, more flexible and can be attached to any object not just products.+Spree 5.2 introduces [Metafields](/v5/developer/core-concepts/metafields), which are a new way to store additional information about an object. Previously, we used Product Properties to enrich products. Metafields are more powerful, more flexible and can be attached to any object not just products.However we now that properties were available in Spree since it's beginning. So we decided to keep them for backward compatibility until Spree 6.0 to give you time to migrate to metafields.diff --git a/docs/developer/upgrades/5.2-to-5.3.mdx b/docs/v5/developer/upgrades/5.2-to-5.3.mdxsimilarity index 98%rename from docs/developer/upgrades/5.2-to-5.3.mdxrename to docs/v5/developer/upgrades/5.2-to-5.3.mdxindex 944742dc97..2285384016 100644--- a/docs/developer/upgrades/5.2-to-5.3.mdx+++ b/docs/v5/developer/upgrades/5.2-to-5.3.mdx@@ -1,10 +1,11 @@---title: Upgrading to Spree 5.3description: This guide covers upgrading a Spree 5.2 application to Spree 5.3.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/5.2-to-5.3"---<Info>- Before proceeding to upgrade, please ensure you're at [Spree 5.2](/developer/upgrades/5.1-to-5.2)+ Before proceeding to upgrade, please ensure you're at [Spree 5.2](/v5/developer/upgrades/5.1-to-5.2)</Info>## Upgrade steps@@ -273,7 +274,7 @@ Spree.admin.tables.orders.add :vendor,partial: 'spree/admin/orders/table/vendor_column'```-See the [Admin Tables documentation](/developer/admin/tables) for more details.+See the [Admin Tables documentation](/v5/developer/admin/tables) for more details.### Tailwind CSS v4 Migrationdiff --git a/docs/developer/upgrades/5.3-to-5.4.mdx b/docs/v5/developer/upgrades/5.3-to-5.4.mdxsimilarity index 92%rename from docs/developer/upgrades/5.3-to-5.4.mdxrename to docs/v5/developer/upgrades/5.3-to-5.4.mdxindex d3edb55846..1bf0741710 100644--- a/docs/developer/upgrades/5.3-to-5.4.mdx+++ b/docs/v5/developer/upgrades/5.3-to-5.4.mdx@@ -1,10 +1,11 @@---title: Upgrading to Spree 5.4description: Upgrade a Spree 5.3 application to Spree 5.4 — remove spree_sample, update gems, run migrations, switch to AdminUserMethods, and backfill image thumbnail IDs.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/5.3-to-5.4"---<Info>- Before proceeding to upgrade, please ensure you're at [Spree 5.3](/developer/upgrades/5.2-to-5.3)+ Before proceeding to upgrade, please ensure you're at [Spree 5.3](/v5/developer/upgrades/5.2-to-5.3)</Info>## Upgrade steps@@ -124,7 +125,7 @@ Prefix length isn't limited by default, but we recommend to keep it short.### Migrate Checkout Zones to Markets-Spree 5.4 introduces [Markets](/developer/core-concepts/markets) as the primary way to manage which countries are available for checkout, along with their currencies and locales. The legacy `checkout_zone` field on the Store model is now deprecated and will be removed in Spree 6.0.+Spree 5.4 introduces [Markets](/v5/developer/core-concepts/markets) as the primary way to manage which countries are available for checkout, along with their currencies and locales. The legacy `checkout_zone` field on the Store model is now deprecated and will be removed in Spree 6.0.New stores automatically get a default market created from their `default_country` — no manual setup needed. For existing stores that used `checkout_zone`, run the migration rake task:@@ -147,8 +148,8 @@ The following Store methods now emit deprecation warnings and will be removed in| Deprecated method | Replacement ||---|---|-| `store.checkout_zone` | Use [Markets](/developer/core-concepts/markets) to manage countries |-| `store.checkout_zone=` | Use [Markets](/developer/core-concepts/markets) to manage countries |+| `store.checkout_zone` | Use [Markets](/v5/developer/core-concepts/markets) to manage countries |+| `store.checkout_zone=` | Use [Markets](/v5/developer/core-concepts/markets) to manage countries |The `store.default_country` reader now returns the first country (by name) from the store's default market. The `store.default_country_iso=` setter still works and is used to set the country when creating a store — a default market is automatically created from it.@@ -258,7 +259,7 @@ And run `bundle install`### (Optional) Install Legacy Product Properties extension-Product Properties have been extracted from Spree core to a separate gem `spree_legacy_product_properties`. Product Properties were already deprecated in favor of [Metafields](/developer/core-concepts/metafields) and disabled by default since Spree 5.1.+Product Properties have been extracted from Spree core to a separate gem `spree_legacy_product_properties`. Product Properties were already deprecated in favor of [Metafields](/v5/developer/core-concepts/metafields) and disabled by default since Spree 5.1.If you have `product_properties_enabled: true` in your Spree configuration or rely on Product Properties in any way, install the extension:diff --git a/docs/developer/upgrades/5.4-to-5.5.mdx b/docs/v5/developer/upgrades/5.4-to-5.5.mdxsimilarity index 93%rename from docs/developer/upgrades/5.4-to-5.5.mdxrename to docs/v5/developer/upgrades/5.4-to-5.5.mdxindex 4a21411ef2..618ce78195 100644--- a/docs/developer/upgrades/5.4-to-5.5.mdx+++ b/docs/v5/developer/upgrades/5.4-to-5.5.mdx@@ -1,10 +1,11 @@---title: Upgrading to Spree 5.5description: Step-by-step guide to upgrading a Spree 5.4 application to Spree 5.5, including gem updates, migrations, and breaking changes to review.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/5.4-to-5.5"---<Info>- Before proceeding to upgrade, please ensure you're at [Spree 5.4](/developer/upgrades/5.3-to-5.4).+ Before proceeding to upgrade, please ensure you're at [Spree 5.4](/v5/developer/upgrades/5.3-to-5.4).</Info>The upgrade is usually completed in five steps:@@ -53,7 +54,7 @@ This is reference material — what `bundle exec rake spree:upgrade` (and equiva### Migrate legacy variant-pinned media-In 5.5 the [product is the default owner of media](/developer/core-concepts/media#product-level-gallery). Existing variant-pinned images keep rendering, but new admin uploads attach to the product. To consolidate both into a single gallery, the upgrade runs:+In 5.5 the [product is the default owner of media](/v5/developer/core-concepts/media#product-level-gallery). Existing variant-pinned images keep rendering, but new admin uploads attach to the product. To consolidate both into a single gallery, the upgrade runs:<CodeGroup>@@ -89,7 +90,7 @@ bundle exec rake spree:media:migrate_master_images_to_product_media BATCH_SIZE=1### Run the Channels upgrade-Spree 5.5 introduces [Sales Channels](/developer/core-concepts/channels) — a per-store distribution surface (online storefront, POS, marketplace integration, wholesale portal). Products are published to a channel via the new `spree_product_publications` join table, and orders are attributed to a channel via `spree_orders.channel_id`.+Spree 5.5 introduces [Sales Channels](/v5/developer/core-concepts/channels) — a per-store distribution surface (online storefront, POS, marketplace integration, wholesale portal). Products are published to a channel via the new `spree_product_publications` join table, and orders are attributed to a channel via `spree_orders.channel_id`.The migrations add a `default` boolean on `spree_channels`, a `store_id` column on `spree_products`, and create the new `spree_product_publications` table — **but they do not seed default channels, attach existing products to a store, or backfill order channels**. That work is done by an idempotent rake task:@@ -120,7 +121,7 @@ The task is fully idempotent — safe to re-run if it fails partway, and a no-op### Reindex products-The last step rebuilds the search index against the configured [search provider](/developer/core-concepts/search-filtering):+The last step rebuilds the search index against the configured [search provider](/v5/developer/core-concepts/search-filtering):<CodeGroup>@@ -247,7 +248,7 @@ The Quantifier short-circuits before any reservation query when this is `false`,### Opt out of rules-based Order Routing-Spree 5.5 introduces [Order Routing](/developer/core-concepts/shipments#order-routing) — a configurable, per-channel pipeline that decides which stock locations fulfill an order. Every store and every channel ships with three default rules (Preferred Location → Minimize Splits → Default Location) that produce sensible behavior out of the box, with no migration work required.+Spree 5.5 introduces [Order Routing](/v5/developer/core-concepts/shipments#order-routing) — a configurable, per-channel pipeline that decides which stock locations fulfill an order. Every store and every channel ships with three default rules (Preferred Location → Minimize Splits → Default Location) that produce sensible behavior out of the box, with no migration work required.If you've heavily customized fulfillment in Spree 5.4 and aren't ready to adopt the new rules engine, you can keep the legacy pre-5.5 routing by switching the store's strategy to `Spree::OrderRouting::Strategy::Legacy`:diff --git a/docs/developer/upgrades/5.5-to-5.6.mdx b/docs/v5/developer/upgrades/5.5-to-5.6.mdxsimilarity index 98%rename from docs/developer/upgrades/5.5-to-5.6.mdxrename to docs/v5/developer/upgrades/5.5-to-5.6.mdxindex a8d181dc09..d65da24432 100644--- a/docs/developer/upgrades/5.5-to-5.6.mdx+++ b/docs/v5/developer/upgrades/5.5-to-5.6.mdx@@ -1,10 +1,11 @@---title: Upgrading to Spree 5.6description: Step-by-step guide to upgrading a Spree 5.5 application to Spree 5.6, including gem updates, migrations, data backfills, and breaking changes to review.+canonical: "https://spreecommerce.org/docs/v5/developer/upgrades/5.5-to-5.6"---<Info>- Before proceeding to upgrade, please ensure you're at [Spree 5.5](/developer/upgrades/5.4-to-5.5).+ Before proceeding to upgrade, please ensure you're at [Spree 5.5](/v5/developer/upgrades/5.4-to-5.5).</Info>The upgrade is usually completed in four steps:diff --git a/docs/v5/developer/upgrades/5.6-to-6.0.mdx b/docs/v5/developer/upgrades/5.6-to-6.0.mdxnew file mode 100644index 0000000000..4e4fb9ecaa--- /dev/null+++ b/docs/v5/developer/upgrades/5.6-to-6.0.mdx@@ -0,0 +1,653 @@+---+title: Upgrading to Spree 6.0+description: Guide to upgrading a Spree 5.6 application to Spree 6.0+hidden: true+canonical: "https://spreecommerce.org/docs/developer/upgrades/5.6-to-6.0"+---++<Info>+ Before proceeding to upgrade, please ensure you're at [Spree 5.6](/v5/developer/upgrades/5.5-to-5.6). Spree 6.0 requires **Rails 8.1** and is the designated breaking-change window for the platform — read the behavioral changes section even if your upgrade runs clean.+</Info>++Spree 6.0 is a major release. The headline changes:++- **Cart and Order are separate models.** `Spree::Cart` owns shopping and checkout; completing checkout copies the cart into an immutable `Spree::Order`. The order state machine is gone.+- **Checkout has no server-side state machine.** Steps are advisory metadata for your frontend; the backend enforces exactly one hard gate — completion.+- **Adjustments are typed rows.** The polymorphic `Spree::Adjustment` is replaced by `Spree::TaxLine`, `Spree::Discount` and `Spree::Fee`.+- **Master Variant** is gone, replaced by a `default_variant_id` foreign key on `Spree::Product`. There's no hidden/dummy Variant created now, the default variant is a real Variant with its own SKU, price, stock, etc.+- **Fulfillment vocabulary.** `Shipment` → `Fulfillment`, `ShippingMethod` → `DeliveryMethod`, `Zone` → `DeliveryZone`, with a pluggable `FulfillmentProvider` strategy.+- **Two-tier services.** Plain services in `app/services`, plus `Spree::Workflow` classes in `app/workflows` for the curated multi-step flows (completion, cancellation, recalculation) — with named steps, instrumentation and extension hooks.++The upgrade is completed in four steps:++1. **Update the Ruby gems**+2. **Run database migrations**+3. **Run data backfills** — convert your existing records into the new schema+4. **Review behavioral changes** — this release changes runtime behavior, not just schema++## How to upgrade++<CodeGroup>++```bash Spree CLI (Docker)+spree upgrade+```++```bash Without Spree CLI+# cd backend if you're in the monorepo root+bundle update+bundle exec rake spree:install:migrations && bin/rails db:migrate+bundle exec rake spree:upgrade+```++</CodeGroup>++Skipping versions and re-running are both safe — `bundle exec rake spree:upgrade` figures out what still needs to happen and does nothing on data that's already migrated.++## What the upgrade does++Reference material — the data backfills `bundle exec rake spree:upgrade` executes. Every task is idempotent.++### Convert incomplete orders into carts++```bash+bundle exec rake spree:migrate_incomplete_orders_to_carts+```++Every order that never completed and was never canceled becomes a `Spree::Cart` with the same token, so in-flight guest and customer checkouts survive the deploy. The cart re-owns the order's line items, fulfillments, payments, payment sessions, reservations and coupon codes; the hollow order row is deleted. Completed and canceled orders are untouched. Orders holding payment sessions convert last, so an interrupted run leaves the riskiest rows for the retry.++### Convert legacy adjustments into typed rows++```bash+bundle exec rake spree:migrate_adjustments_to_typed_rows+```++Rebuilds `spree_adjustments` into `Spree::TaxLine`, `Spree::Discount` and `Spree::Fee` rows. Orders whose typed sums do not reconcile with the stored totals are left untouched and flagged (`private_metadata['typed_adjustments_frozen']`) for manual review instead of silently changing money.++### Backfill fulfillment and delivery naming++```bash+bundle exec rake spree:migrate_shipping_to_delivery+bundle exec rake spree:migrate_zones_to_delivery_zones+bundle exec rake spree:migrate_calculator_bounds_to_delivery_method_rules+```++Moves stored strings, statuses and class names to the fulfillment/delivery vocabulary, converts delivery-referenced `Spree::Zone` records into `Spree::DeliveryZone` with typed members, and converts FlatRate calculator eligibility bounds into `Spree::DeliveryMethodRule` records.++### Remove master variants++```bash+bundle exec rake spree:remove_master_variant+```++Products now carry a `default_variant_id` foreign key; `is_master` is gone from the models. (The physical column drop lands in 6.1.)++### Categories and collections++```bash+bundle exec rake spree:migrate_taxons_to_categories_and_collections+```++Taxons become `Spree::Category` (hierarchy) and automatic taxons become `Spree::Collection` (flat, rule-based). `Spree::Taxon` remains as an alias for one release.++### Move rich text out of Action Text++```bash+bundle exec rake spree:migrate_rich_text_to_columns+```++Category and collection descriptions, policy bodies, and order and customer internal notes move from `action_text_rich_texts` into text columns on their own tables. Per-locale rows land in the model's translation table.++Run this **after** two earlier steps, both load-bearing: the categories step re-points the rows from `Spree::Taxon` to `Spree::Category` so this one can still find them, and the customers step populates `spree_customers` — a note is copied onto the customer row it belongs to, so running before those rows exist would treat every legacy customer note as orphaned and skip it for good. Following the manifest order handles this for you.++Content is sanitized on the way in, and **the 6.0 allowlist is much narrower than 5.6's**: it permits only what the dashboard's editor emits — paragraphs, headings, `strong`/`em`/`s`/`u`/`code`, `pre`, `blockquote`, lists, `hr`, `br` and links. Tables, images, `div`/`span`, inline `style` and arbitrary `class` attributes are no longer permitted. Text inside a stripped tag survives; its formatting does not. The exceptions are `script` and `style`, which are removed along with their contents — a script body would otherwise reappear as visible text.++If your descriptions rely on richer markup, permit it in an initializer **before** running the task and before saving anything under 6.0:++```ruby+# config/initializers/spree.rb+Spree::RichTextSanitizer.allowed_tags += %w[table thead tbody tr th td img]+Spree::RichTextSanitizer.allowed_attributes += %w[src alt colspan rowspan]+```++The Action Text rows are left in place as a rollback path and are dropped with the tables in 6.1.++Once this has run, **Spree no longer loads Action Text.** `spree_core` dropped `require 'action_text/engine'` — along with `action_cable/engine`, which nothing in Spree used — and a fresh install no longer creates the tables. The rake task requires Action Text itself, so the upgrade works either way. If your own code uses `has_rich_text`, Action Text view helpers, or Action Cable, require what you need in `config/application.rb` (apps generated from the Spree starter already do):++```ruby+require 'action_text/engine'+require 'action_cable/engine'+```++### Backfill order coupon codes++```bash+bundle exec rake spree:backfill_order_coupon_codes+```++`spree_orders` gains a `coupon_code` column (parity with carts). Historical placed orders applied coupons only through the promotion join tables — this fills the column from the attached coupon-code record (or the applied single-code promotion) so admin filtering and the serializer answer consistently for old orders.++### Markets on orders++```bash+bundle exec rake spree:backfill_order_markets+```++Orders missing a market get the store default — `market` is required on carts and orders in 6.0.++## The Cart/Order split++The single biggest change. What used to be one `Spree::Order` living through checkout and beyond is now two models:++- **`Spree::Cart`** (`spree_carts`, prefixed IDs `cart_...`) owns the shopping and checkout phase: line items, addresses, payments-in-progress, delivery proposals, promotions, stock reservations. Carts have **no status column** — `completed_at` is the only lifecycle marker.+- **`Spree::Order`** is created *by completion* — the cart is copied into it (line items, fulfillments, addresses, typed money rows — **copies, never shared rows**). Orders carry `status` (`draft` / `placed` / `canceled`) and are money-frozen once placed.++Consequences to review:++- **Completed carts are read-only.** The cart is retained after completion (abandonment analytics, idempotent replay) but rejects every write. Post-checkout life belongs to the order.+- **Completion is idempotent.** `Spree::Carts::Complete` guards with a unique `spree_orders.cart_id` index and a `completing_at` lock: a double-clicked Place Order returns the same order, a crashed completion replays safely, and a pre-capture payment failure rolls the draft order back and re-points payments to the cart.+- **The guest token carries over** from cart to order, so confirmation pages keep working with the credential the guest already holds.+- **Dual concrete FKs, not polymorphism.** Records owned by either side (`LineItem`, `Fulfillment`, `TaxLine`, `Discount`, `Fee`, `Payment`, `StockReservation`) carry nullable `cart_id` + `order_id` with an exactly-one rule and an `#owner` method. Code that assumed `line_item.order` is always present must read `line_item.owner`.+- **Shared model surface** lives in `Spree::Purchase::*` concerns (addresses, taxation, store credits, gift cards, digital items, payment processing, market/channel/currency/locale resolution) — included by both Cart and Order. Decorators targeting `Spree::Order` methods that moved should decorate the concern or the new owner.++## Checkout without a state machine++`Spree::Order` no longer has a `state` column, a state machine, or the `checkout_flow` DSL. If your app customized checkout with `checkout_flow`, `go_to_state`, `insert_checkout_step`, `remove_checkout_step` or `remove_transition` — those APIs are gone (not deprecated: the machine they configured no longer exists).++The replacement model:++- **Steps are advisory.** `cart.checkout_steps`, `current_checkout_step` and `completed_checkout_steps` are *derived* from cart data — there is no stored step and no server-side sequencing. Clients may write any checkout field in any order. "Steps" are a grouping label telling your frontend which page an unmet requirement belongs to.+- **One hard gate.** `Spree::Carts::Complete` is the only place checkout is enforced. It validates the full requirement battery (line items, email, addresses, delivery selection, payment coverage, per-item stock, discontinued products, guest policy) and returns structured `{ step, field, code, message }` errors.+- **`Spree::Checkout::Registry` is the extension surface.** One declaration serves both the advisory feed and the completion gate:++```ruby+# config/initializers/spree.rb+Rails.application.config.to_prepare do+ Spree::Checkout::Registry.add_requirement(+ step: :payment,+ field: :po_number,+ message: 'PO number is required',+ satisfied: ->(cart) { cart.metadata['po_number'].present? },+ applicable: ->(cart) { cart.customer.present? }+ )+end+```++ The requirement appears in the Cart API's `requirements` array (so a storefront rendering the feed generically needs zero changes) *and* blocks completion. `register_step` adds whole steps (spliced into `checkout_steps` at `before:`/`after:` anchors); built-in steps are customized through `Registry.base_steps` — an ordered `{ name => applicability }` hash you can mutate directly (`base_steps.delete('confirm')`).+- **The API `requirements` array now carries a stable `code`** on every entry (`email_required`, `out_of_stock`, `guest_checkout_not_allowed`, ...). Additive change — existing consumers keep working.+- **The delivery requirement is keyed `delivery_method`, not `shipping_method`.** Its entry is now `{ step: 'delivery', field: 'delivery_method', code: 'delivery_method_required' }`. A storefront that renders the feed generically needs no change; one that keys off the field or code to highlight a specific input must switch both tokens. The `Spree.t('checkout_requirements.shipping_method_required')` translation key was renamed to `checkout_requirements.delivery_method_required` — override it under the new key.+- **"Logic between steps" has no backend home by design.** Side effects hang off data writes (workflow hooks such as `Carts::Complete`'s `before_finalize` and `Carts::AddItem`'s `after_item_added`) and events (`cart.updated`, `order.placed`) — not step transitions.++## Statuses: derived, then persisted++`payment_state` and `shipment_state` machine columns are replaced by `payment_status` and `fulfillment_status` — stored, indexed, and recomputed from payment/refund/fulfillment records by a single writer, `Spree::Orders::UpdateStatuses`. The legacy names remain as read aliases for one release.++Behavior to review:++- Nothing else writes these columns. If your code assigned `order.payment_state = 'paid'`, replace it with the underlying records (payments/refunds) and let the recompute derive.+- The `payment_status` domain gains `overcharged` and `voided`; `fulfillment_status` includes `backorder`. Money comparisons are quantized to currency precision and refunds are netted before comparing.+- A completed payment updates **only the payment side of the ledger** (`payment_total` + statuses). It never re-sums item or adjustment money.+- Fulfillment is a fact: a fulfilled fulfillment is never downgraded by later payment-state changes.++## Recalculation on write++Transition-triggered recalculation is gone with the machine. Instead:++- **`Spree::Carts::RecalculateTotals`** is the single totals seam: money inputs, typed-row regeneration (promotions via the winner-only adjuster, tax via `Spree.tax_provider`), folding and one persist. It runs on the writes that matter — item changes, address/market changes (which also re-price items and rebuild delivery proposals) — not on step transitions.+- Promotion eligibility is evaluated against **current** totals in the same recalculation — a cart crossing a coupon threshold gets the discount on that recalculation, not the next one.+- **Completed orders are money-frozen.** Typed rows are never regenerated post-placement; recalculation only re-sums them. Post-placement money edits go through the explicit admin services (`Orders::Discounts::*`, `Orders::Fees::*`), which write rows and re-sum.+- `Spree::OrderUpdater` and `Spree::CartUpdater` remain as deprecated shells — every method warns and runs the full recalculation. Removed in 6.1.++## Completion, in one workflow++`Spree::Orders::Complete` is the one home for everything that happens when an order becomes placed — payment processing (when needed), fulfillment finalization, placement, coupon/gift-card redemption, digital auto-fulfillment, statuses, and the `order.placed` event. Checkout reaches it through `Carts::Complete`; admin/B2B draft completion calls it directly (`payment_pending: true` places without processing payments for invoice-later flows).++- **`Order#finalize!` is deprecated** (removed in 6.1) and delegates to the workflow. Behavioral change: finalizing an **already-completed order is now a no-op** — the workflow halts idempotently instead of re-running side effects.+- **Completion side effects moved out of the model.** Newsletter subscription, checkout account creation and risk assessment run in the synchronous `Spree::OrderPlacedSubscriber` on the `order.placed` event. Decorators that patched `finalize!` should become event subscribers or `before_finalize` hook handlers.+- **`order.placed` is the completion event.** `order.completed` still fires as a deprecated alias for one release (webhook consumers should migrate; wildcard subscribers can dedupe on the `deprecated_alias_of` metadata marker).+- `Order.register_update_hook` no longer runs during completion.++## Addresses++The full address surface is shared by Cart and Order through `Spree::Purchase::Addresses`, which means cart checkout regains behavior that 5.x orders had:++- Address writes **deduplicate** against the customer's address book and **promote** checkout addresses to the customer's defaults (quick-checkout wallet addresses excluded).+- `ship_address_id=` / `bill_address_id=` are **ownership-guarded**: an address not owned by the record's customer resolves to `nil`.+- A signed-in customer entering checkout gets blank address slots **auto-filled from their saved defaults**.+- **`use_billing` is deprecated** (removed in 6.1): the shipping address is canonical — use `use_shipping` to copy ship → bill.++## Returns, exchanges and claims++The `ReturnAuthorization → CustomerReturn → Reimbursement` chain is replaced by three first-class records that each belong directly to an order: **`Spree::Return`** (items come back, money goes back), **`Spree::Exchange`** (items come back, different items go out), and **`Spree::Claim`** (something went wrong in delivery — no items required back).++The old classes are **gone with no bridge**, so calls raise `NameError`:++| Removed | Use instead |+|---|---|+| `Spree::ReturnAuthorization` | `Spree::Return` or `Spree::Exchange` |+| `Spree::CustomerReturn` | `Spree::Return` — receiving is a status on the same record |+| `Spree::Reimbursement`, `Spree::ReimbursementType` | `Spree::Returns::Refund` (a workflow, not a model) |+| `Spree::ReturnItem` | `Spree::ReturnLineItem` / `Spree::ExchangeLineItem` / `Spree::ClaimLineItem` |+| `Spree::ReturnItem::EligibilityValidator::*` | the `validate` hook — see below |+| `Spree::ReturnAuthorizationReason` | `Spree::ReturnReason` (constant alias kept until 6.1, with a warning) |++<Note>+ **The legacy tables are not dropped.** They stay through 6.1 as the data migration's source and rollback path. Run `spree:upgrade:migrate_returns` to copy the history onto the new models — it's resumable, and it aborts if any row fails so an upgrade can't silently proceed on partial history.+</Note>++### No state machines++New records carry a plain `status` string with an inclusion validation. Every transition is a workflow — `Spree::Returns::Approve`, `Returns::Receive`, `Returns::Refund`, `Exchanges::Fulfill`, `Claims::Resolve`, and so on. **Nothing happens in a model callback or transition callback**, so code that hooked `before_transition` on the old machines has no equivalent; move it to a workflow hook or an event subscriber.++Statuses are extensible but additive only, through `Spree::HasStatus`:++```ruby+Spree::Return.add_status('inspecting', after: 'received')+```++### Eligibility is a hook, not a validator chain++`ReturnItem::EligibilityValidator::Default` chained five validators. Only one was policy; the rest were invariants, so they moved to different places:++| Old validator | Where the rule lives now |+|---|---|+| `TimeSincePurchase` | `Spree::Returns::EligibilityValidator`, registered on the `validate` hook |+| `OrderCompleted` | inline guard in `Returns::Create` |+| `InventoryShipped` | structural — only fulfillment items can be returned, and quantities are checked against what shipped |+| `NoReimbursements` | quantity math — prior return line items are subtracted, so units can't come back twice |+| `RMARequired` | gone: the `Return` **is** the request, so there is nothing to require |++Core ships exactly one policy rule — a return window read from `market.preferred_return_window_days` (default 30), per market because return windows are a regional legal matter. **Staff can override it**: when `created_by` is present the window is advisory, so a supervisor can accept a late return without a code change.++<Warning>+ Four returns settings are **deprecated and read by nothing** — they still exist so applications don't crash at boot, but they have no effect and now emit a deprecation warning when read or written:++ | Deprecated setting | Use instead |+ |---|---|+ | `return_eligibility_number_of_days` | `preferred_return_window_days` on `Spree::Market`, or a `returns.create.validate` hook |+ | `restock_inventory` | `Spree::ReturnLineItem#resellable`, decided per line item at receiving |+ | `expedited_exchanges`, `expedited_exchanges_days_window` | `Spree::Exchange` and the `Exchanges::Fulfill` workflow |+</Warning>++Replace it by swapping the handler:++```ruby+Spree.hooks.unregister('returns.create.validate', 'Spree::Returns::EligibilityValidator')+Spree.hooks.register('returns.create.validate', 'MyStore::ReturnPolicy')+```++A handler receives the workflow (so it can read `order`, `items`, `created_by`, `order.market`) and calls `workflow.reject!(message)` to veto. Every one of the fifteen transitions has a leading `validate` hook, so the same seam gates approving, receiving and refunding.++<Warning>+ `requires_manual_intervention?` has no equivalent. The old validators could mark an item eligible-but-flagged for manual review; a handler now either accepts or vetoes. If you relied on that middle state, model it explicitly — an added status, or a metafield your handler sets.+</Warning>++### Other behavioral changes++- **`Return#refunded_total` counts store credits.** Store credit is a separate ledger and never creates a `Spree::Refund` row, so the old sum reported zero for a store-credit refund.+- **`Order#outstanding_balance` dropped its reimbursement term** rather than replacing it — refunds already net out of `payment_total`, so that term was double-counting.+- **The reimbursement email is now `Spree::ReturnMailer#refunded_email`**, sent on `return.refunded` (in the optional `spree_emails` gem, like the other transactional mail).+- **`Refund#originator`** points at the new records.+- Events are `return.requested` / `.approved` / `.received` / `.refunded` / `.canceled`, and the matching `exchange.*` and `claim.*` families.++## Dependency injection changes++6.0 introduces `*_workflow` keys for the flows that graduated to the workflow tier. The old `*_service` keys **stay settable and readable one release so applications don't crash at boot — but a legacy write is stashed, not applied**: a class written against the old service contract is not interchangeable with the workflow the new call sites consume. Reads return your stashed class (legacy code calling its own override keeps working), falling back to the workflow. Removed in 6.1.++| Legacy key (stash-only) | 6.0 key | Resolves to |+|---|---|---|+| `cart_add_item_service` | `cart_add_item_workflow` | `Spree::Carts::AddItem` |+| `cart_recalculate_service` | `cart_recalculate_workflow` | `Spree::Carts::Recalculate` |+| `carts_complete_service` | `carts_complete_workflow` | `Spree::Carts::Complete` |+| `order_cancel_service` | `order_cancel_workflow` | `Spree::Orders::Cancel` |+| `order_complete_service` | `order_complete_workflow` | `Spree::Orders::Complete` |+| `shipment_update_service` | `fulfillment_update_service` | `Spree::Fulfillments::Update` |++New seams with no legacy counterpart:++| Key | Resolves to | Purpose |+|---|---|---|+| `cart_recalculate_totals_workflow` | `Spree::Carts::RecalculateTotals` | the single totals seam |+| `order_recalculate_totals_workflow` | `Spree::Orders::RecalculateTotals` | order twin (post-placement re-sum) |+| `order_resume_workflow` | `Spree::Orders::Resume` | resume canceled orders |+| `order_discount_create_service` | `Spree::Orders::Discounts::Create` | renamed from `order_add_manual_discount_service` (never released) |+| `order_update_statuses_service` | `Spree::Orders::UpdateStatuses` | the sole status writer |++Removed keys (their classes no longer exist): `carts_validate_service` (completion validation is `Spree::Checkout::Requirements` directly), plus the dead legacy `Spree::Cart::*` service namespace registrations.++If you override a workflow seam, subclass the shipped workflow (or implement the same `perform` keyword contract) — workflow arguments are plain Ruby keywords, so a mismatch raises `ArgumentError` at call time, not silently.++## Removed in 6.0++These were deprecated in 5.x and are **gone now** — there is no bridge, so calls raise `NoMethodError`. Most were one-line delegations to a replacement that already exists.++| Removed | Use instead |+|---|---|+| `Product#default_image`, `#featured_image`, `#primary_image` | `#primary_media` |+| `Variant#default_image`, `#primary_image` | `#primary_media` |+| `Address#user_default_billing?`, `#user_default_shipping?` | `#is_default_billing?`, `#is_default_shipping?` |+| `OptionType#color?` | `#color_swatch?` |+| `Category#set_store` | `#ensure_store` |+| `Category.for_taxonomy` | `.for_store` |+| `Store#admin_users` | `#users` |+| `Store#supported_shipping_zones` | `#countries_with_shipping_coverage` |+| `Spree.searcher_class` | `Spree.search_provider` |+| `Spree.admin_user_class.spree_admin_created?` | `.spree_admin.exists?` |+| `BaseMailer#set_email_locale` | wrap the action body in `with_store_locale(store) { ... }` |+| `Asset#styles`, `ImageMethods#generate_url`, `#original_url` | Active Storage variants with `cdn_image_url` |+| `Spree::ImageMethods`, `Spree::NumberAsParam` (concerns) | deleted — `NumberAsParam` was already a no-op; prefixed IDs come from `Spree::PrefixedId` |+| `Product.with_option`, `.with`, `.in_name`, `.in_name_or_keywords`, `.in_name_or_description`, `.with_ids`, `.for_user` | `.with_option_value`, `.search`, `where(id: ids)` |+| `Product.add_search_scope` | plain `scope :name, -> { ... }` |+| `Spree::Image::Configuration::ActiveStorage` | deleted — an empty no-op module; all logic lives in `Spree::Asset` |+| `Spree::OrderRouting::Strategy::Legacy` | `Spree::OrderRouting::Strategy::Rules` (see below) |+| `private_metafields` association | read `custom_fields` and filter, or query `Spree::CustomField.admin_only` |++### Custom fields replace metafields++The metafields system is now custom fields: `Spree::CustomField` and `Spree::CustomFieldDefinition`, stored in `spree_custom_fields` and `spree_custom_field_definitions`. The legacy class names, the concern, and the reader methods all keep working for one release with a deprecation warning (see the table further down), so most applications need no code change to upgrade.++Two things do change under you, both handled by `db:migrate`:++- **Visibility is a boolean.** The tri-state `display_on` column collapses into `storefront_visible`. Definitions that were `back_end` become `storefront_visible: false`; everything else becomes `true`. The `front_end`-only value never meant hidden-from-staff and folds into `true`.+- **Two columns are renamed.** `name` becomes `label`, and `metafield_type` becomes `field_type`. Reading `field_type` returns the API token (`short_text`) rather than the Ruby class name; use `field_type_class_name` when you need the class.+- **Rich-text values leave Action Text.** `Spree::CustomFields::RichText` stores sanitized HTML in the same `value` column as every other type, so reading `value` returns a String rather than an `ActionText::RichText`. Existing bodies are copied across by the migration; the Action Text rows stay behind as a rollback path until 6.1. Code calling `custom_field.value.body` should read `value` directly.++Two behavior notes for extension authors: `Spree::Metadata` no longer includes the custom-fields concern (metadata is the private, schemaless system — include `Spree::HasCustomFields` explicitly if a model needs both), and rich-text values are now sanitized on save, so markup outside the allowlist is stripped rather than stored.++**BREAKING — product CSV.** Custom-field columns are now prefixed `custom_field.` instead of `metafield.` (for example `custom_field.custom.material`). Exports emit the new prefix and imports only recognise the new prefix, so update any saved import templates and any integration that reads the export. A file still using the old prefix imports without its custom-field values rather than failing.++### The Legacy order-routing strategy is gone++`Spree::OrderRouting::Strategy::Legacy` — the pre-5.5 escape hatch that delegated straight to `Spree::Stock::Coordinator` and consulted no routing rules — is removed and no longer registered in `Spree.order_routing.strategies`.++A store or channel still carrying `preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Legacy'` **keeps working**: `Order#order_routing_strategy` ignores unregistered classes, logs a warning, and falls back to `Strategy::Rules`. Clear the stale preference to silence the warning — note that saving such a record now fails validation, since the value is no longer in the registry.++`Spree::Stock::Coordinator` itself stays — cart fulfillment building, exchanges, and claims still use it.++### `belongs_to` is required by default++Spree models followed Rails' pre-5 rule, where a `belongs_to` was optional+unless you said otherwise. They now follow the modern default: a `belongs_to`+is **required** unless it is declared `optional: true`.++Two consequences for an application built on Spree:++- **Your own models change with it.** Anything inheriting from `Spree::Base`+ picks up the new default, so an association that is legitimately blank now+ needs `optional: true` on it. A model that relied on the old behaviour will+ start failing validation until you say which associations are optional.+- **The message changed.** A missing association reports `"must exist"` rather+ than `"can't be blank"`. Code that matches on the old wording — a test, or a+ client reading `details` out of a 422 — needs updating.++Setting a record's association to `nil` and saving it is the quickest way to+tell whether an association is required.++### `Store.default` no longer builds a store++`Spree::Store.default` returned an **unpersisted** `Store.new(default: true)` when no default store existed. It now returns `nil`.++This matters more than it looks: `Spree::Current.store` falls back to `Store.default`, and every `Spree::SingleStoreResource` model resolves its own `store` from `Spree::Current.store`. Without a default store, those records now fail validation with "Store must exist" instead of silently attaching to a throwaway store.++Make sure a default store exists before creating store-scoped records, and set `Spree::Current.store` in jobs, rake tasks, and tests that run outside a request.++### The `DefaultPrice` concern is gone — `price_in` / `set_price` is the interface++`Spree::DefaultPrice` and the `enable_legacy_default_price` setting are removed, along with the `has_one :default_price` association on `Variant`. Prices live in `spree_prices`, one row per currency, and a price is always an **amount plus a currency** — there is no longer an implicit "the" price.++The single-currency accessors are gone from both `Variant` and `Product`:++| Removed | Use instead |+|---|---|+| `variant.price`, `product.price` | `variant.price_in(currency).amount` or `amount_in(currency)` |+| `variant.price = x`, `product.price = x` | `variant.set_price(currency, x)` |+| `variant.default_price` | `variant.price_in(currency)` |+| `variant.currency`, `product.currency` | the currency is an argument now — pass the one you mean |+| `display_price`, `display_amount` | `price_in(currency).display_amount` |+| `compare_at_price=` | `set_price(currency, amount, compare_at_amount)` |+| `display_compare_at_price` | `price_in(currency).display_compare_at_amount` |+| `price_including_vat_for(opts)` | `price_in(currency).price_including_vat_for(opts)` |+| `has_default_price?` | `prices.base_prices.exists?(currency: currency)` |++The `compare_at_price` **reader** (which resolves against `cost_currency`) is unchanged on both `Variant` and `Product` — only the writer is gone. So are the `price_in` / `amount_in` / `compare_at_amount_in` readers.++Also note:++- **Ransack:** `default_price` is no longer a searchable association on `Variant`; query `prices` instead.+- **Prices in permitted params:** the dead `:price` and `:compare_at_price` entries are gone. Prices were already written as nested `prices: [{ amount:, currency: }]` under variants — the top-level keys had no writer behind them. (`Spree::PermittedAttributes` itself is removed in 6.0 — see below.)+- Localized number parsing still happens: `Spree::Price#amount=` runs `Spree::LocalizedNumber.parse`, so `set_price(currency, '1,599.99')` works as `price=` did.+- The variant validation that inferred a missing price from the product's default variant is gone. Set prices explicitly (the product and variant factories already do).++### `Spree::PermittedAttributes` is removed++The global permitted-attributes registry is gone, with no deprecation bridge. It+existed so the Rails admin and storefront could share one allowlist; both are+removed in 6.0, and API v3 declares its attributes in the controller.++Removed alongside it: `Spree::Core::ControllerHelpers::StrongParameters` (the+`permitted_*_attributes` helper methods it mixed into controllers) and the+fallback that inferred an attribute list from the model name.++Attributes you pushed from an initializer are now declared on the model, and+standard resource endpoints append them to their own allowlist — so one+declaration still covers the model's create and update endpoints.++#### How to migrate++**1. Find every call site.** The constant and the helper methods are both gone,+so a missed reference raises `NameError` or `NoMethodError` the first time that+code runs — loudly, but not necessarily at boot:++```bash+grep -rn "PermittedAttributes" app config lib+grep -rnE "permitted_[[:alnum:]_]+_attributes" app config lib+```++The second pattern is deliberately broad: the helper module generated one+`permitted_*_attributes` method per registry key, so there were dozens of them.++**2. Decide what each attribute actually is.** Most fall into one of three+buckets, and only the last needs this hook:++| What you were adding | Where it goes in 6.0 |+| --- | --- |+| A merchant-managed field (text, number, dropdown) | [Custom Fields](/developer/core-concepts/custom-fields) — no code, and filterable/sortable |+| Config for an STI type you register (promotion rule, delivery method rule, …) | `additional_permitted_attributes` on that subclass, as before — unchanged |+| A real database column your extension added to a core model | `additional_permitted_attributes` on the model |++**3. Point each declaration at the model.** It stays in your initializer — only+the receiver changes, from the global registry to the model itself:++```ruby config/initializers/spree.rb+# Before+Spree::PermittedAttributes.product_attributes << :brand_id++# After+Spree::Product.additional_permitted_attributes += [:brand_id]+```++Use `+=`, not `=` — the list is per model, and assigning replaces whatever+another extension already added. `<<` raises a `FrozenError`: the default is a+frozen shared array, so mutating it in place would leak your attribute onto every+other model.++Declare only attributes of your own. Redeclaring a key the controller already+permits (`metadata`, `prices`) does not widen it — strong parameters keeps the+last filter for that key, so the controller's own would be replaced by yours.++Entries are `params.permit` fragments, so collections and nested structures keep+the shapes you already know: `[:brand_id, { region_ids: [] }]`.++**4. Fix your own controllers.** If you subclassed a Spree v3 resource+controller and relied on the attribute list being inferred from the model name,+declare it now:++```ruby+class BrandsController < Spree::Api::V3::Admin::ResourceController+ protected++ def model_class+ Spree::Brand+ end++ # Before: no such method — the base class inferred `brand_attributes`+ # from the model name. Now you say what you accept.+ def resource_permitted_attributes+ [:name, :slug, :description]+ end+end+```++Declaring neither `resource_permitted_attributes` nor `permitted_params` raises+`NotImplementedError` on the first write, so this surfaces in your test suite+rather than silently permitting a stale list.++**5. Verify a write actually persists.** A declaration that never reaches a+controller fails silently — strong parameters drop the unpermitted key, the+request still returns 200, and the column keeps its old value. Assert on the+saved record, not the response status:++```ruby+patch "/api/v3/admin/products/#{product.prefixed_id}",+ params: { brand_id: brand.id }, headers: headers++expect(product.reload.brand_id).to eq(brand.id)+```++If that assertion fails, the endpoint is not consulting your declaration. Check+whether the controller overrides `permitted_attributes` — that method is where+the extension attributes are appended, so overriding it replaces them. Override+`resource_permitted_attributes` instead.++<Warning>+ Two endpoints deliberately ignore the hook because their parameters are+ authorization data rather than resource data: API keys (`scopes`, `key_type`)+ and invitations (`role_id`). Adding attributes there needs a controller+ decorator, not a model declaration.+</Warning>++STI types registered through a Spree registry (promotion rules and actions,+delivery method rules, commission rules) already used+`additional_permitted_attributes` and need no changes — the hook simply moved up+to `Spree::Base`.++### `StateChange` and `LogEntry` are gone++`Spree::StateChange` and `Spree::LogEntry` are removed — the models, the `state_changes` associations on `Order`, `Payment` and `Fulfillment`, the `log_entries` associations on `Payment` and `Refund`, and everything that wrote to them. Both were write-only: nothing in Spree read the rows back, and the admin screens that displayed them are gone.++**Events are the audit trail now.** Instead of querying state-change rows, subscribe to the lifecycle events that already fire on every meaningful transition: `order.placed`, `order.canceled`, `payment.completed`, `payment.voided`, `fulfillment.ready`, `fulfillment.fulfilled`, `fulfillment.canceled`, `fulfillment.resumed`, and the rest. If you need a persistent history, write it from a subscriber.++**Gateway responses are no longer stored in your database.** `LogEntry` kept every gateway response as serialized YAML. For transaction forensics, use your payment provider's dashboard — `Payment#gateway_dashboard_payment_url` links straight to the transaction — or `Spree::PaymentSession`, which holds the gateway-side state for session-based providers.++The `spree_state_changes` and `spree_log_entries` tables are **not dropped until 6.1**, so your existing rows survive the upgrade. If you want the history long-term, export it before upgrading to 6.1.++## Deprecated in 6.0, removed in 6.1++Every rename keeps the legacy name working for one release with a deprecation warning. The notable ones:++| Deprecated | Use instead |+|---|---|+| `Order#finalize!` | `Spree.order_complete_workflow` |+| `Order#updater`, `Spree::OrderUpdater`, `Spree::CartUpdater` | `#recalculate_totals!` / `#update_statuses!` |+| `Order#shipping_discount` | `#fulfillment_discount` |+| `Order#special_instructions` | `#customer_note` (column renamed) |+| `Order#promo_total`, `#item_count`, `#ship_total` | `#discount_total`, `#total_quantity`, `#delivery_total` (columns renamed) |+| `use_billing` / `clone_billing_address` | `use_shipping` (shipping address is canonical) |+| `Fulfillment#ship`, `#ship!`, `#shipped?`, `#can_ship?`, `#shipping_method`, `#add_shipping_method` | `#fulfill`, `#fulfill!`, `#fulfilled?`, `#can_fulfill?`, `#delivery_method`, `#add_delivery_method` |+| `LineItem#target_shipment` | `#target_fulfillment` |+| `Order#create_proposed_shipments` / `#create_proposed_fulfillments` | `#rebuild_fulfillments!` (Cart ships with the new name only) |+| `Order#remove_out_of_stock_items!` | cart-side only (`Spree::Carts::RemoveOutOfStockItems`) |+| `Order#delivery_required?` | `#delivery_step_required?` — digital and pickup are deliveries too; this asks whether the customer must choose a delivery option |+| `Order#requires_ship_address?` | `#shipping_address_required?` — decided by the selected delivery methods (`DeliveryMethod#requires_address?`); digital, pickup, and pickup-point deliveries need no customer address |+| `requirements[].field` / `.code` `shipping_method` (Store API) | `delivery_method` / `delivery_method_required` — no bridge; clients keying off the delivery requirement must switch both tokens |+| `Cart#number` (Store API field) | `id` — carts have no order-style number; the field mirrors the prefixed ID for one release |+| `order.completed` event | `order.placed` |+| Calling cart services with `order:` kwargs | `cart:` kwargs |+| `OrderWalkthrough` (testing support) | factories: `:cart_ready_for_delivery`, `:cart_ready_to_complete`, `:completed_order_with_totals` |+| `Spree::Metafield`, `Spree::MetafieldDefinition`, `Spree::Metafields::*` | `Spree::CustomField`, `Spree::CustomFieldDefinition`, `Spree::CustomFields::*` |+| `include Spree::Metafields` | `include Spree::HasCustomFields` |+| `#set_metafield`, `#get_metafield`, `#has_metafield?` | `#set_custom_field`, `#get_custom_field`, `#has_custom_field?` |+| `metafields` / `public_metafields` associations | `custom_fields` / `storefront_custom_fields` |+| `.with_metafield_key`, `.with_metafield_key_value` | `.with_custom_field_key`, `.with_custom_field_key_value` |+| `Spree.metafields` | `Spree.custom_fields` |+| `CustomFieldDefinition#name`, `#metafield_type`, `#display_on` | `#label`, `#field_type`, `#storefront_visible` (columns renamed) |+| `Spree::SearchProvider::Meilisearch` | `SpreeMeilisearch::SearchProvider` (moved to the `spree_meilisearch` gem) |+| `Spree::SearchProvider::ProductPresenter` | `SpreeMeilisearch::ProductPresenter` (moved to the `spree_meilisearch` gem) |++## Meilisearch moved to its own gem++Meilisearch is no longer part of `spree_core`. Stores using the Database provider (the default) need to do nothing.++If you set `Spree.search_provider` to the Meilisearch provider, add the gem and update the class name:++```ruby+# Gemfile+gem 'spree_meilisearch'++# config/initializers/spree.rb+Spree.search_provider = 'SpreeMeilisearch::SearchProvider'+```++Your `MEILISEARCH_URL` and `MEILISEARCH_API_KEY` settings are unchanged, and **no reindex is needed** — the documents have the same shape. Applications that subclassed the document presenter should inherit from `SpreeMeilisearch::ProductPresenter` instead.++The old class names keep working for one release, so an application that only names them in an initializer boots with a deprecation warning rather than an error — but the gem must be installed either way, since the classes now live there.++## Staff permissions: roles are data++Permission sets are **removed with no bridge**. Staff roles now hold flat permission keys from one catalog — the same `read_<resource>` / `write_<resource>` vocabulary secret API keys use — and are managed as data: in the dashboard (Settings → Roles), through the Admin API (`/api/v3/admin/roles`), or in seeds. Code no longer defines what a role can do.++| Removed | Use instead |+|---|---|+| `Spree::PermissionSets::*` (all classes) | catalog keys on the role row: `Spree::Role#permissions` |+| `Spree.permissions.assign(:role, [sets])` | the role editor, `POST /api/v3/admin/roles`, or plain ActiveRecord in seeds |+| Custom permission sets with record-level rules | Replace the ability class: `Spree::Dependencies.ability_class = 'MyApp::Ability'` |+| `Spree::ApiKey::SCOPES` | `Spree::ApiKey.known_scopes` (derived from the catalog) |++Old initializers fail loudly at boot: the set constants raise `NameError`, and `Spree.permissions.assign` raises with directions. **Recreate your custom roles before deploying** — a pre-existing role row comes up with no permissions, so staff holding it are locked out (fail closed) until its permissions are filled in:++```ruby+# db/seeds.rb — "roles as code" is plain ActiveRecord now+Spree::Role.find_or_create_by!(name: 'support')+ .update!(permissions: %w[read_orders read_customers])+```++Storefront customers are not part of this system: the old `:default` role and `DefaultCustomer` set are gone, customers never resolve roles, and the Store API no longer consults CanCanCan at all — customer authorization is ownership-scoped queries plus `Spree::Storefront::AccessPolicy` (swappable via `Spree::Dependencies.storefront_access_policy_class`). If an extension added storefront `can` rules, move them into an access-policy subclass or a checkout workflow `validate` hook. Extensions register their resources into the catalog once, which makes them grantable to roles **and** mintable as API-key scopes:++```ruby+Spree.permissions.register_resource(:reviews, group: :catalog, subjects: -> { [SpreeReviews::Review] })+```++Two enforcement changes on the Admin API:++- **JWT staff pass the same per-controller key gate as secret keys.** A request whose principal lacks `<read|write>_<resource>` gets a 403 with `details.required_permission` naming the missing key.+- **Staff endpoints moved out of the `settings` scope.** `/admin_users`, `/invitations`, and `/roles` now require the new `read_staff` / `write_staff` scopes; secret keys minted with `settings` before 6.0 lose those endpoints. `/countries` and `/locales` became scope-exempt reference data.++### Rich-text fields read as plain text plus HTML++**Writes are unchanged.** `description` and `internal_note` still take the value, and that value is still HTML — the same as 5.6, so no integration needs updating.++Reads are where 6.0 differs. Every rich-text field now returns both shapes:++| Resource | Plain text | HTML |+| --- | --- | --- |+| Product, Category, Collection | `description` | `description_html` |+| Order, Customer | `internal_note` | `internal_note_html` |++Two consequences worth checking in your own code:++- **Hydrate editors from `*_html`.** The plain field is tag-stripped, so binding an editor to `description` and saving it back would flatten the markup on every save.+- **The field holds HTML.** That is true of every writer — the Admin API, CSV import, the console — so send markup, not plain text with newlines in it.++Both internal-note serializers now return the pair. Previously orders exposed only plain text and customers only HTML.++Stored markup is also held to a narrower allowlist than 5.6 — see [the rich-text migration](#move-rich-text-out-of-action-text) for what is permitted and how to widen it.++## For extension authors++- **Don't reach for model business methods from services** — 6.0 code style writes behavior inline in service/workflow steps; models keep data, validations, predicates and persistence primitives. Extensions patching removed model methods (`finalize!` internals, updater hooks) should move to workflow hooks (`Spree.hooks.register('carts.complete.before_finalize') { |flow| ... }` — handlers receive the workflow instance) or event subscribers.+- **Store-scoped data is single-owner.** `Product`, `Promotion` and `PaymentMethod` `belongs_to :store`; the `stores: [...]` writers are gone. Multi-store sharing lives in the `spree_multi_store` extension.+- The Store API v3 contract is stable across the split — cart endpoints keep their shapes; `requirements` gains `code` (and renames the delivery entry's field/code to `delivery_method`, see above), and serializer `number` on carts is bridged as described above.++<Warning>+ This guide tracks the 6.0 development line and will grow until release. If a behavioral change you hit isn't documented here, treat it as a documentation bug and report it.+</Warning>diff --git a/docs/v5/developer/upgrades/quickstart.mdx b/docs/v5/developer/upgrades/quickstart.mdxnew file mode 100644index 0000000000..335f99db3a--- /dev/null+++ b/docs/v5/developer/upgrades/quickstart.mdx@@ -0,0 +1,38 @@+---+title: Quickstart+description: Learn how to upgrade your Spree application+canonical: "https://spreecommerce.org/docs/developer/upgrades/quickstart"+---++Keeping your Spree installation up-to-date is essential to keep it safe and secure. Each Spree version brings new features, enhancements and bug fixes so it's greatly beneficial for you and your clients to upgrade frequently.++The upgrade process is fairly easy and well described. Of course, it all boils down to the level of customizations and the way you've customized your Spree applications.++We strongly advise upgrading Spree incrementally, rather than in one big go.++## Support++If you're stuck and would want to get some professional help, you can [contact us directly](https://spreecommerce.org/contact/) and request a quote for our consulting services.++## Release types++Spree development follows a shifted version of [Semantic Versioning](https://semver.org/):++**Patch Z, eg. 4.2.1**++Only bug fixes, no API changes, no new features. Except as necessary for security fixes.++**Minor Y, eg. 4.2.0**++New features, may contain API changes Serve as major versions of Semver. Breaking changes are paired with deprecation notices in the previous minor or major release.++**Major X, eg. 4.0.0**++New features, will likely contain API changes. The difference between Spree minor and major releases is the magnitude of breaking changes and is usually reserved for special occasions.++## Security++Our Security policy is [described here](/developer/security).++When a release series is no longer supported, it's your own responsibility to deal with bugs and security issues. We may provide backports of some critical security fixes.+diff --git a/docs/v5/user/customers/assign-store-credits.mdx b/docs/v5/user/customers/assign-store-credits.mdxnew file mode 100644index 0000000000..0961af0051--- /dev/null+++ b/docs/v5/user/customers/assign-store-credits.mdx@@ -0,0 +1,64 @@+---+title: "Issue Store Credits"+description: "Learn how to issue store credits to customers in the Spree admin dashboard."+canonical: "https://spreecommerce.org/docs/user/customers/assign-store-credits"+---++Store credits allow you to add funds directly to a customer’s account. Unlike gift cards, store credits are tied to a specific customer and cannot be transferred. They are commonly used for refunds, compensation, or loyalty rewards.++In more advanced use cases, store credits can serve as the primary payment method - particularly in B2B scenarios where customers operate on prepaid balances or agreed credit thresholds that they draw from over time.++## How to Issue Store Credits++To issue store credits, navigate to **Customers** in the admin dashboard.++++Find and click on the customer to open their profile page.++++You can issue store credit in two ways:+- Click the **three-dot menu** in the top right corner and select **Add Store Credit**+- Or click **Add Store Credit** directly from the analytics section at the top of the customer profile++++Clicking on either of these will redirect you to the store credit creation form.++## Configure the Store Credit++++Complete the following fields:+- **Amount** - The value of the store credit+- **Currency** - Select the currency (if your store supports multiple currencies)+- **Memo** - Optional internal note explaining the reason for issuing the credit++Click **Create** to assign the credit. The balance will immediately be available to the customer and visible in the **Store Credits** section of the customer profile.++## Edit Store Credits++++To edit a store credit assignment:++1. Navigate to the customer profile+2. Scroll to the **Store Credits** section+3. Click on a store credit assignment to be redirected to that credit’s form+4. Click **Edit** in the Details section+5. Modify the store credit assignment as necessary and click **Update**++## Delete Store Credits++++To remove a store credit:++1. Navigate to the customer profile+2. Scroll to the **Store Credits** section+3. Click on a store credit assignment to be redirected to that credit’s form+4. Click the **three-dot menu** in the top-right corner+5. Click **Delete** from the menu++<Note>Deleting store credit will permanently remove the assigned balance from the customer’s account.</Note>diff --git a/docs/v5/user/customers/create-customer.mdx b/docs/v5/user/customers/create-customer.mdxnew file mode 100644index 0000000000..ceadaf56cd--- /dev/null+++ b/docs/v5/user/customers/create-customer.mdx@@ -0,0 +1,64 @@+---+title: "Create a Customer"+description: "Learn how to create new customers in Spree Commerce as an admin."+canonical: "https://spreecommerce.org/docs/user/customers/create-customer"+---++Depending on your business model, you might need to manually create customer accounts—for example, when processing phone or in-person orders, handling wholesale clients, or migrating data from another platform.++This ensures customer details are accurately recorded in the system, enabling better order tracking, personalized service, and targeted marketing.++## Create a New Customer++To a create a new customer, navigate to **Customers** in the admin dashboard.++++Click **New Customer** in the top-right corner to open the creation form.++++Fill in the following customer fields:++- First Name+- Last Name+- Phone Number (optional)+- Tags (optional)++<Note>Tags help you categorize and segment customers based on purchasing behavior or account type, and can improve filtering, reporting, and personalization.</Note>++Once you’ve filled in the required fields, click **Create**, and you’ll be redirected to the customer’s profile page.++++From here, you can add additional customer details and manage everything related to the customer - including their orders, store credit, gift cards, and more.++## Add Shipping Address++++To add the customer’s shipping address, follow these steps:++1. Locate the **Shipping Address** section of the customer’s profile+2. Click **Add** to open the address form+3. Fill in the customers shipping details and click **Create**++Once created, you’ll be able to preview the customer’s shipping address.++++<Note>If your store has the Google Maps API connected, a map will appear alongside the saved address, pinpointing the customer's location. This can help visually confirm the accuracy of the address.</Note>++## Add Billing Address++By default the billing address is set to **Same as Shipping Address**.++To use a different billing address:++1. Click **Edit** under the **Billing Address** section.+2. Select **Add New Address**, enter the billing address, and click **Create**.++## Customer Login Access++In order for the customer to access their account, they must initiate a password reset on the storefront using the email address tied to their profile.diff --git a/docs/v5/user/customers/customer-groups.mdx b/docs/v5/user/customers/customer-groups.mdxnew file mode 100644index 0000000000..acabac2f7c--- /dev/null+++ b/docs/v5/user/customers/customer-groups.mdx@@ -0,0 +1,76 @@+---+title: "Segment shoppers with Customer Groups"+sidebarTitle: "Customer Groups"+description: "Create Customer Groups in Spree to segment shoppers and tailor pricing, promotions, tax rules, and access for B2B accounts, VIPs, or wholesale buyers."+canonical: "https://spreecommerce.org/docs/user/customers/customer-groups"+---++Customer Groups let you segment your customers into defined lists, which can then be used to personalize pricing, limit access to promotions, or power other business rules.++## Why use Customer Groups?++On their own, groups are just lists. The value comes from what you attach to them — and how Spree uses group membership to automatically personalise what each buyer sees.++**Pricing tiers** — By pairing a customer group with a [<u>Price List</u>](https://spreecommerce.org/docs/user/manage-products/price-lists), every member of that group automatically sees their correct prices the moment they log in. The Price List can override base prices across your entire catalog, or just on specific products. You can have as many groups and price lists as you need — one per customer tier, one per named account, or one per region — and Spree applies the right one without any manual work. When you add a new customer to a group, they inherit the pricing immediately.++**Exclusive promotions** — Promotion rules can be restricted to specific customer groups, so a discount code or automatic offer only applies to the customers it's meant for. Useful for loyalty rewards, trade-only offers, or onboarding incentives for new wholesale accounts.++**Single storefront, multiple experiences** — Because pricing and promotions are tied to the buyer's account rather than to separate stores or URLs, retail and trade customers can shop side by side on the same storefront. Public visitors see standard prices; logged-in trade buyers see theirs. No duplicate stores to maintain, no separate login portals to manage.++### Example: Wholesale, Dealer, and VIP tiers++An industrial supplier runs three buyer types from a single storefront:++- **Wholesale** — registered trade buyers who see a standard wholesale price across the catalog+- **Dealer** — authorized dealers with a deeper discount tier and access to exclusive product bundles+- **VIP** — high-volume accounts with individually negotiated pricing++Each group has its own Price List. When a buyer logs in, Spree checks their group membership and applies the correct prices automatically.++<Note>For a full walkthrough of this setup, see [<u>Set Up Wholesale Pricing</u>](https://spreecommerce.org/docs/user/how-to/wholesale-pricing).</Note>++## Create a Customer Group++To create a new customer group, navigate to **Customers → Customer Groups** in the admin dashboard.++++Here you'll see an overview of all existing customer groups, including the number of customers in each.++Click the **New Customer Group** button in the top right to begin setup.++## Add Group Details++++In the creation form, add:++- **Name** — This is how the group will appear in admin interfaces+- **Description** — Use this field to describe the purpose of the group, e.g. "North America wholesale buyers" or "Early access testers" (optional)++Click **Create** to save the new group.++## Add Customers to the Group++++Once the group is created, you'll be taken to its detail view.++To add customers to the group, click the **Add Customers** button, and a side panel will open where you can search and select customers to add.++++Check the boxes next to the customers you want to add, then click **Add Selected**.++++That's all there is to it — your customer group is now ready to use in price lists, promotions, and more.++## Remove Customers from a Group++To remove customers from a group, select the checkboxes next to the customers you want to remove, then click **Remove from Group** in the actions menu at the bottom of the screen.++## Next Steps++- [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists) — create pricing rules that target specific customer groups+- [<u>Set Up Wholesale Pricing</u>](https://spreecommerce.org/docs/user/how-to/wholesale-pricing) — step-by-step guide to building wholesale pricing tiers with customer groupsdiff --git a/docs/v5/user/customers/customer-profile.mdx b/docs/v5/user/customers/customer-profile.mdxnew file mode 100644index 0000000000..88cb6ac9af--- /dev/null+++ b/docs/v5/user/customers/customer-profile.mdx@@ -0,0 +1,143 @@+---+title: "Customer Profiles"+description: "Learn how to access and interpret the Customer Profile in the Spree admin dashboard."+canonical: "https://spreecommerce.org/docs/user/customers/customer-profile"+---++The Customer Profile gives you a complete view of a customer’s activity, order history, and account details - all in one place. It helps you better understand purchasing behavior, identify high-value customers, and provide faster, more personalized support.++## Accessing a Customer Profile++To access a customer’s profile, navigate to **Customers** in the admin dashboard.++++Find the customer you’d like to review (use search and filters if needed), and click on the customer’s name to open their profile.++++The profile page is divided into several sections, each providing important information about the customer.++## User Analytics++++At the top of the page, you’ll see a summary of key customer metrics:++- Total Amount Spent+- Number of Orders+- Average Order Value+- Store Credits+ - Shows the value of store credits the customer has available+ - You can assign store credits here by clicking **Add Store Credit**+- Created At date, i.e., when they became a customer++These metrics give you a quick snapshot of the customer’s engagement and lifetime value.++## Details++++This section contains core account information, including:++- Email address+- Phone number+- First and last name+- Email marketing opt-in status+- Assigned [<u>Customer Groups</u>](https://spreecommerce.org/docs/user/customers/customer-groups)+- Customer tags++<Note>You can use **tags** and **customer groups** to segment customers for promotions, pricing rules, or internal organization.</Note>++## Addresses++### **Shipping Address**++++This section displays the customer’s default shipping address.++<Note>If a Google Maps API key is connected, a map preview with a pinned location will also be shown.</Note>++### **Billing Address**++++Displays the billing address or indicates **“Same as shipping address”** if that option is selected.++## Internal Note++++The Internal Note section displays any notes added by admins related to the customer.++These notes are not visible to the customer and can be used to:++- Document special agreements or pricing arrangements+- Flag account concern+- Record support interactions+- Add context for other team members++Internal notes help ensure your team has the full picture when assisting the customer.++## Last Order Placed++++This section shows a summary of the most recent order placed by the customer.++You can click the order number (e.g., R394161122) to see the full order details page.++## Orders++++The Orders subsection displays a full list of all completed orders associated with the customer.++You can:++- Search within the customer’s orders+- Apply filters+- Sort and select which columns to display++This makes it easy to quickly find specific transactions.++## Draft Orders++++Draft Orders include:++- Abandoned carts+- Admin-created orders that are not yet completed+- Orders without attached payments++This section is useful for following up on incomplete purchases or manually created orders.++## Gift Cards++++Displays all gift cards assigned to the customer, including:++- Current balance+- Amount used+- Currency+- Status++For more information on issuing gift cards, please refer to our [<u>Issuing Gift Cards</u>](https://spreecommerce.org/docs/user/customers/issue-gift-card) article.++## Store Credits++++Displays any store credit assigned to the customer, along with usage history.++Store credits are commonly used for refunds, loyalty rewards, or manual adjustments.++In more advanced use cases, store credits may function as the primary payment method - especially in B2B environments where companies maintain a prepaid balance or approved credit limit and settle invoices periodically.++To learn more about store credits, please refer to our [<u>Assigning Store Credits</u>](https://spreecommerce.org/docs/user/customers/assign-store-credits) article.+++In summary, the Customer Profile gives you a centralized view of everything related to a customer - making it easier to support them, reward loyalty, and resolve issues quickly.diff --git a/docs/v5/user/customers/edit-customer.mdx b/docs/v5/user/customers/edit-customer.mdxnew file mode 100644index 0000000000..4f9a91c01f--- /dev/null+++ b/docs/v5/user/customers/edit-customer.mdx@@ -0,0 +1,94 @@+---+title: "Editing Customers"+description: "Learn how to edit customer profiles in the Spree Commerce admin dashboard."+canonical: "https://spreecommerce.org/docs/user/customers/edit-customer"+---++You may need to edit a customer’s profile to correct contact details, update addresses, manage tags, or adjust account-related settings. This is especially common when handling phone orders, B2B accounts, or customer support requests.++## How to Edit a Customer++To edit a customer, navigate to **Customers** in the admin dashboard.++++Find and click the customer you’d like to update to open their **Customer Profile** page.++++From here, there are several sections of the customer profile that you may edit when necessary.++## Contact Details++++In the **Details** section, click **Edit** to open the edit form and modify:++- Email address+- Phone number+- First and last name+- Email marketing opt-in / opt-out status+- Tags+- Customer Group (if applicable)++Click **Save** to apply your changes.++## Shipping Address++++In the **Shipping Address** section, click **Edit** to reveal the address editor form, and update the customer’s default shipping address as required.++<Note>Updating the shipping address in the customer profile does not change the address on existing or outstanding orders. To modify an order’s shipping address, edit the order directly from the **Orders** tab.</Note>++## Billing Address++++In the **Billing Address** section, click **Edit** to modify the customer’s default billing address.++You’ll then be able to choose between:++- **Same as shipping address**, or+- **Add a new address**++Selecting **Add a new address** will reveal the address form, where you can enter the updated billing details. Click **Update** to apply your changes.++<Note>As with shipping addresses, updating the billing address here will not affect existing orders.</Note>++## Internal Notes++++The **Internal Note** section allows admins to leave private notes about a customer (for example, special handling instructions, account context, or support history).++To add or update an internal note:++1. Click **Edit** in the Internal Note section+2. Enter your note+3. Click **Save**++<Note>Internal notes are only visible to admins and are never shown on the storefront.</Note>++## Issue Gift Cards++++You can issue a gift card directly from the customer profile.++Click the **three-dot menu** in the top right corner and select **Add Gift Card**.++For detailed instructions, refer to the [<u>Issue a Gift Card</u>](https://spreecommerce.org/docs/user/customers/issue-gift-card) support article.++## Issue Store Credits++++You can also assign store credit to a customer account.++Either:++- Click the **three-dot menu** and **Add Store Credit**, or+- Use the **Add Store Credit** button in the analytics section at the top of the profile.++For step-by-step guidance, see the [<u>Issue Store Credits</u>](https://spreecommerce.org/docs/user/customers/assign-store-credits) support article.diff --git a/docs/v5/user/customers/exporting-customers.mdx b/docs/v5/user/customers/exporting-customers.mdxnew file mode 100644index 0000000000..24d89ce865--- /dev/null+++ b/docs/v5/user/customers/exporting-customers.mdx@@ -0,0 +1,49 @@+---+title: "Export Customers"+description: "Learn how to export customers records to CSV in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/customers/exporting-customers"+---++In Spree you can, export your customer database for reporting, segmentation, or integration with external tools such as email marketing platforms or CRM systems.++Doing so can make it easier to analyze trends, review engagement, and manage customer relationships outside of Spree when needed.++## How to Export Customers++To export customers, navigate to **Customers** in the admin dashboard.++++From here you may optionally apply filters and export the records you require.++### Apply Filters++If you want to export a specific segment rather than your entire customer list, apply filters before exporting.++You can use the **Filters** button to narrow results by fields such as:++- Email marketing (opt-in status)+- Location+- Created at / Updated at+- First Name+- Last Name+- Tags++To learn more about filters, refer to our [<u>Searching Customers</u>](https://spreecommerce.org/docs/user/customers/searching-customers) article.++<Note>If no filters are applied, the export will include all customers, regardless of your choice in the next step.</Note>++### Export++++Once your desired view is set, click **Export** in the top-right corner.++You’ll be prompted to confirm whether you want to export:++- **Filtered records** (only the customers currently shown), or+- **All records**++After confirming, a CSV file will be generated and sent to the email address associated with your admin account.++<Note>Using filters before exporting allows you to create targeted customer lists for campaigns, reporting, or operational needs.</Note>diff --git a/docs/v5/user/customers/issue-gift-card.mdx b/docs/v5/user/customers/issue-gift-card.mdxnew file mode 100644index 0000000000..825adab2e1--- /dev/null+++ b/docs/v5/user/customers/issue-gift-card.mdx@@ -0,0 +1,62 @@+---+title: "Issue a Gift Card"+description: "Learn how to issue gift cards to customers in the Spree admin dashboard."+canonical: "https://spreecommerce.org/docs/user/customers/issue-gift-card"+---++Gift cards are prepaid balances that can be redeemed like cash on future purchases. They’re commonly used for promotions, customer service gestures, loyalty rewards, or as products sold directly to customers.++In Spree, you can issue gift cards to individual customers or generate them in bulk for later distribution. This guide covers how to issue a gift card to a specific customer.++## How to Issue a Gift Card++To issue a gift card, navigate to **Customers** in the admin dashboard.++++Find and click the customer who should receive the gift card to open their customer profile.++++Click the **three-dot menu** in the top right corner, and select **Add a Gift Card**.++++You’ll be redirected to the gift card creation form.++## Configure the Gift Card++++Complete the following fields:++- **Code** - Leave blank to have Spree automatically generate a unique code, or enter one manually.+- **Amount** - The value of the gift card.+- **Currency** - Select the currency the gift card should be issued in.+- **Expires At** - Optional expiration date. Leave blank for a non-expiring gift card.++Click **Create** to issue the gift card. It will immediately appear in the customer’s **Gift Cards** section.++## Edit a Gift Card++++To modify a gift card:++1. Go to the customer’s profile+2. Scroll to the **Gift Cards** subsection+3. Click on the gift card to be redirected that gift card's form+4. Click **Edit** in the Settings section+5. Make your changes and click **Update**++## Delete a Gift Card++++To delete a gift card:++1. Go to the customer’s profile+2. Scroll to the **Gift Cards** subsection+3. Click on the gift card to be redirected to that gift card's form+4. Click **three-dot menu** in the top-right corner+5. Click **Delete**diff --git a/docs/v5/user/customers/searching-customers.mdx b/docs/v5/user/customers/searching-customers.mdxnew file mode 100644index 0000000000..009e8b30a0--- /dev/null+++ b/docs/v5/user/customers/searching-customers.mdx@@ -0,0 +1,78 @@+---+title: "Searching Customers"+description: "Learn how to search for customers in the Spree admin dashboard."+canonical: "https://spreecommerce.org/docs/user/customers/searching-customers"+---++Quickly finding the right customer is essential for providing efficient support, reviewing order history, updating account details, or managing marketing preferences.++Spree’s updated table view makes it easy to search, sort, and filter customer records with precision.++## How to Search for Customers++To search for customers, navigate to **Customers** in the admin dashboard.++++At the top of the page, you’ll find the search bar along with sorting, column, and filter controls.++## Search Bar++++Use the search bar to quickly locate a customer by:++- Email address+- First name+- Last name++Results update based on your query, helping you find specific profiles instantly.++## Sorting & Columns++The new table interface allows you to customize how customer data is displayed.++### **Sort**++++Click on the **Sort by** dropdown to select the field you like to sort by, and select whether you’d like the results to be in ascending or descending order.++### **Columns**++++Use the column selector to choose which fields are visible in your table view. This allows you to tailor the layout based on what information is most relevant to your workflow.++## Filters++++For more advanced searches, click **Filters** to build custom filter rules.++You can create filter groups using **AND** / **OR** logic and apply conditions using the following operators:++- equals+- does not equal+- greater than+- greater than or equal+- less than+- less than or equal+- is any of+- is none of+- is empty+- is not empty++### **Available Filter Fields**++You can filter customers by:++- Email marketing (opted in or not)+- Location+- Created at+- Updated at+- First Name+- Last Name+- Tags++Multiple filters can be combined to narrow down results - for example, finding customers who have opted into email marketing and were created within a specific timeframe.diff --git a/docs/v5/user/how-to/multi-currency-pricing.mdx b/docs/v5/user/how-to/multi-currency-pricing.mdxnew file mode 100644index 0000000000..f35ea90959--- /dev/null+++ b/docs/v5/user/how-to/multi-currency-pricing.mdx@@ -0,0 +1,80 @@+---+title: "Set Up Multi-Currency Pricing"+description: "Learn how to configure your store to display and sell in multiple currencies."+canonical: "https://spreecommerce.org/docs/user/how-to/multi-currency-pricing"+---++When you sell to customers in different countries, you'll want each customer to see prices in their local currency. In Spree, this involves two steps: creating a Market for each currency, then setting a base price in that currency on your products.++In this guide, we'll walk through a common scenario — a US-based store adding a German market so customers in Germany can browse and buy in EUR.++<Note>This guide covers multi-currency pricing — different currencies for different regions. If you need different prices within the same currency across regions (e.g., separate EUR prices for Germany, France, and Spain), see [<u>Set Up Multi-Region Pricing</u>](https://spreecommerce.org/docs/user/how-to/multi-region-pricing) instead.</Note>++## Prerequisites++Before you start, you should have at least one active market already configured — typically your home market. In this example, a US market with USD is already set up.++## 1. Create a Market for the New Currency++The Market must be created first. Until a currency is assigned to a Market, you will not be able to set prices for other currencies (in this case, EUR).++To create a Market, navigate to **Settings → Markets** in the admin dashboard.++++Click **New Market** to open the creation form.++++Fill in the details for your new market. For a German market:++- **Name** — `Germany`+- **Default Country** — `Germany`+- **Currency** — `EUR`+- **Default Locale** — `DE` for German, or `EN` if your storefront runs in English+- **Tax Inclusive** — check this if prices should display with VAT included, which is standard practice in EU markets+- **Default** — leave unchecked, since the US market is already the default++Click **Create**, and Germany will now appear in your Markets list alongside your US market.++++## 2. Set EUR Prices on Your Products++With the EUR market in place, the currency switcher is now available in the product editor. You'll need to add a EUR price to every product you want to sell in Germany — any product without a EUR price will not be shown to customers browsing in that market.++To set the EUR prices, navigate to **Products** and open the product you want to update.++++Where you find the currency switcher depends on whether the product has variants. For single-variant products, look in the **Pricing** section. For multi-variant products, look in the **Variants** section, where pricing and inventory are managed together in a combined table.++++Enter the EUR price for this product (e.g., `89.00` for a product priced at `99.00` USD) and click **Update** to save.++++Repeat this process for every product you want to make available to German customers.++<Warning>Any product without a EUR price set will not be displayed to customers browsing in the Germany market. Make sure all products you want to sell in a market have a price in that market's currency.</Warning>++<Note>Multi-currency prices can also be set via CSV import. See the [<u>Product Import File Template</u>](https://spreecommerce.org/docs/user/manage-products/product-import-file-template) for reference.</Note>++## 3. Verify on the Storefront++Once your market and product prices are set up, verify the setup by visiting your storefront.++1. Look for the market switcher in your storefront's navigation. If you're using the Spree Next.js starter storefront, this appears in the navigation bar.+2. Switch to **Germany / EUR**+3. Confirm that product prices are now displayed in EUR++++If a product does not appear after switching to EUR, check that a EUR price has been saved for that product in the product editor.++## Next Steps++- [<u>Set Up Multi-Region Pricing</u>](https://spreecommerce.org/docs/user/how-to/multi-region-pricing) — charge different prices within the same currency for different markets+- [<u>Markets</u>](https://spreecommerce.org/docs/user/settings/markets) — full reference for configuring Markets+- [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists) — reference for setting up price overrides and rulesdiff --git a/docs/v5/user/how-to/multi-region-pricing.mdx b/docs/v5/user/how-to/multi-region-pricing.mdxnew file mode 100644index 0000000000..addf23f5fe--- /dev/null+++ b/docs/v5/user/how-to/multi-region-pricing.mdx@@ -0,0 +1,106 @@+---+title: "Set Up Multi-Region Pricing"+description: "Learn how to charge different prices within the same currency across multiple regional markets."+canonical: "https://spreecommerce.org/docs/user/how-to/multi-region-pricing"+---++When you sell to customers across different countries that share a currency — for example, France, Germany, and Spain all using EUR — you may want to set different prices for each market rather than showing everyone the same EUR price. In Spree, you do this using Price Lists: you create a market for each region, then create a Price List that targets that market and overrides the base EUR prices for your products.++In this guide, we'll walk through a common scenario — a store with an existing German market (EUR) adding France and Spain as separate markets with their own regional pricing.++<Note>This guide covers multi-region pricing — different prices within the same currency across regions. If you need different currencies for different regions (e.g., USD for the US and EUR for Germany), see [<u>Set Up Multi-Currency Pricing</u>](https://spreecommerce.org/docs/user/how-to/multi-currency-pricing) instead.</Note>++## Prerequisites++Before you start, you should have:++- At least one active market already configured with EUR as its currency. In this example, a Germany market with EUR is already set up and your products have EUR prices.+- Familiarity with how Price Lists work. See [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists) for a full reference.++## 1. Create Markets for France and Spain++Each region needs its own Market in Spree before you can target it with a Price List.++To create Markets, navigate to **Settings → Markets** in the admin dashboard.++++Click **New Market** to open the creation form.++++Fill in the details for France:++- **Name** — `France`+- **Default Country** — `France`+- **Currency** — `EUR`+- **Default Locale** — `FR` for French, or `DE` if your storefront runs in German+- **Tax Inclusive** — check this if prices should display with VAT included, which is standard practice in EU markets+- **Default** — leave unchecked++Click **Create**, then repeat this process to create the Spanish market, setting **Default Country** to `Spain` and **Default Locale** to `ES`.++Once done, all three markets — Germany, France, and Spain — will appear in your Markets list.++++## 2. Create a Price List for Each Market++With your markets in place, you'll now create a Price List for each one. A Price List targeted at a specific market will override your base EUR prices for customers shopping in that market.++To create Price Lists, navigate to **Products → Price Lists** in the admin dashboard and click **New Price List**.++++Fill in the details for France:++- **Name** — e.g., `France Pricing`+- **Description** — optional, but useful for other admins (e.g., `Regional EUR prices for the French market`)+- **Start Date / End Date** — leave blank if this pricing should apply indefinitely++Click **Create** to open the price list editor.++### Add a Market Rule++In the price list editor, click **Add Rule** and select **Market** from the rule type dropdown. Select **France** from the market options.++++This ensures the price list only applies to customers browsing in the French market.++### Add Products and Set Prices++Click **Add Products** to open the product selector. Search for and select the products you want to price differently for France, then click **Add Selected**.++Once the products appear in the list, click **Edit Prices** to open the price editor. Make sure **EUR** is selected in the currency switcher, then enter the regional prices for France in the **Price** column.++++Click **Save** to apply the prices, then click **Activate** in the top right to make the price list live (or **Schedule** if it has a future start date).++Repeat this entire process to create a second price list for Spain — name it `Spain Pricing`, set the Market rule to **Spain**, and enter the appropriate EUR prices for Spanish customers.++<Warning>Any product you don't add to a regional price list will fall back to its base EUR price. If you want France and Spain customers to see different prices, every relevant product needs to be included in the respective price list.</Warning>++## 3. Verify on the Storefront++Once your markets and price lists are active, verify that the correct prices appear for each region.++1. Visit your storefront and look for the market switcher in the navigation. If you're using the Spree Next.js starter storefront, this appears in the navigation bar.+2. Switch to **France / EUR** and note the price shown for a product you included in the France price list.+3. Switch to **Spain / EUR** and confirm the price changes to reflect the Spain price list.+4. Switch back to **Germany / EUR** and confirm the base EUR price is shown (since Germany has no regional price list).++++If a product shows the base EUR price instead of the regional price, check that:++- The product has been added to the correct price list+- The price list is set to **Active**+- The Market rule on the price list is correctly set to the intended market++## Next Steps++- [<u>Set Up Multi-Currency Pricing</u>](https://spreecommerce.org/docs/user/how-to/multi-currency-pricing) — sell in different currencies for different regions+- [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists) — full reference for rules, volume pricing, and customer group pricing+- [<u>Markets</u>](https://spreecommerce.org/docs/user/settings/markets) — full reference for configuring Marketsdiff --git a/docs/v5/user/how-to/multiple-languages.mdx b/docs/v5/user/how-to/multiple-languages.mdxnew file mode 100644index 0000000000..76d76ca79f--- /dev/null+++ b/docs/v5/user/how-to/multiple-languages.mdx@@ -0,0 +1,97 @@+---+title: "Set Up Multiple Languages"+description: "Learn how to sell in multiple languages by configuring locales, translating products, categories, and policies in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/how-to/multiple-languages"+---++Spree lets you present your store in multiple languages — so customers in France see content in French, customers in Germany see content in German, and so on. Languages are tied to your Markets configuration, which means you set up a locale per market and then translate your content to match.++In this guide, we'll walk through enabling additional languages, translating your product catalog in bulk using the translations importer, and making manual adjustments to individual products, categories, and store policies.++## 1. Set Up Markets with Additional Locales++Languages in Spree are configured through Markets. Each market has a **Default Locale** — the language customers see when they browse that market. Before any translation work can begin, you need at least one market set up with a non-default locale.++Navigate to **Settings → Markets** and click **New Market** for each region you want to add.++++When creating or editing a market, set the following:++- **Default Locale** — the primary language for this market (e.g., `FR` for French, `DE` for German)+- **Supported Locales** — any additional languages customers can switch to within that market++<Note>Before you can set up a Market for a country, make sure that country is included in a configured Zone. See [<u>Settings → Zones</u>](https://spreecommerce.org/docs/user/settings/zones) for setup instructions.</Note>++Click **Create** once you've configured the new market. Once your markets are saved, the locales you've configured will appear in the **Products → Translations** page, ready for you to start filling in translated content.++## 2. Translate Products in Bulk Using the Translations Importer++The fastest way to translate a large product catalog is to export your existing content, fill in the translations, and import it back. Navigate to **Products → Translations**.++++The coverage table at the top shows you how many products have been translated for each locale, so you can track your progress at a glance.++### Export your catalog for translation++Click **Export** in the top-right corner, then confirm by clicking **Export** in the modal. A download link will be sent to your admin email address. The exported file contains your product content in your default language, with empty columns for each additional locale — ready to be filled in.++### Fill in the translations++Open the exported CSV file and fill in the translated content for each locale column. This includes product names, descriptions, and any other translatable fields. Save the file when done.++### Import the translated file++Click **Import** in the top-right corner to open the import side panel.++++1. Drag and drop your translated CSV file into the upload area, or click **browse files** to select it.+2. Select the delimiter used in your file (comma, pipe, semicolon, or tab).+3. Click **Create** to proceed to the field mapping step.+4. Review the field mapping and adjust any columns that weren't automatically matched, then click **Continue** to submit.++Once submitted, you'll be taken to a progress screen where you can monitor the import. Any rows with errors will be flagged with a message so you can fix and re-import them.++## 3. Manually Translate Individual Products++For one-off adjustments, the quickest way is to update translations directly from **Products → Translations**. Find the product in the list and click its name to open the translation drawer.++++Fill in or update the translated fields for each locale — name, description, and any other translatable content — then save when done.++<Note>Translations can also be edited from within the product editor itself. Open the product, select the **Translations** from the three-dot menu in the top right corner, and update the fields there. Both methods produce the same result.</Note>++## 4. Translate Categories++Navigate to **Products → Categories** and click on the category you want to translate to open the category configurator.++++Click the **three-dot menu** in the top-right corner of the configurator and select **Translations**. This opens the translations side panel.++++Switch between locales using the locale selector and enter the translated category name for each. Close the panel when done.++For subcategories, the process is the same — click the subcategory to open its editor, click the three-dot menu, and add translations in the side panel.++## 5. Translate Store Policies++Navigate to **Settings → Policies** and click on the policy you want to translate to open the editor.++++Click the **three-dot menu** in the top-right corner and select **Translations** to open the translations side panel. Switch between locales and enter the translated name and content for each, then close the panel when done.++++Repeat this process for each policy you want to make available in additional languages.++## Next Steps++- [<u>Settings → Markets</u>](https://spreecommerce.org/docs/user/settings/markets) — full reference for configuring markets and locales+- [<u>Products → Translations</u>](https://spreecommerce.org/docs/user/manage-products/translations) — full reference for the translations overview and bulk importer+- [<u>Set Up Multi-Region Pricing</u>](https://spreecommerce.org/docs/user/how-to/multi-region-pricing) — configure market-specific pricing alongside your language setupdiff --git a/docs/v5/user/how-to/regional-volume.mdx b/docs/v5/user/how-to/regional-volume.mdxnew file mode 100644index 0000000000..ca31afc7a5--- /dev/null+++ b/docs/v5/user/how-to/regional-volume.mdx@@ -0,0 +1,104 @@+---+title: "Set Up Regional Volume Pricing"+description: "Learn how to offer market-specific volume discounts across multiple regions using Price Lists in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/how-to/regional-volume"+---++Regional volume discounts let you offer quantity-based price breaks that are specific to each market. For example, a customer ordering 25 units in the US sees a USD discount, while a customer ordering the same quantity in Germany sees the equivalent EUR discount — and the thresholds and rates can differ by market too.++In Spree, you do this by combining a Market rule and a Volume rule on each Price List using **Match All** logic. Each market gets its own set of tiered price lists, and Spree applies the correct one based on where the customer is shopping and how many units they're ordering.++In this guide, we'll set up two volume tiers for each of three markets: US (USD), Germany (EUR), and France (EUR).++<Note>This guide assumes your DE and FR markets are already configured and your products have EUR base prices set. If not, follow [<u>Set Up Multi-Currency Pricing</u>](https://spreecommerce.org/docs/user/how-to/multi-currency-pricing) first. For volume pricing without a regional split, see [<u>Set Up Volume Pricing</u>](https://spreecommerce.org/docs/user/how-to/volume-pricing). For regional wholesale pricing using Customer Group rules, see [<u>Set Up Regional Wholesale Pricing</u>](https://spreecommerce.org/docs/user/how-to/regional-wholesale).</Note>++## Prerequisites++Before you start, you should have:++- Markets configured for US, Germany, and France, with EUR base prices set on all products you want to include. See [<u>Set Up Multi-Currency Pricing</u>](https://spreecommerce.org/docs/user/how-to/multi-currency-pricing) for the full walkthrough.+- A clear set of volume thresholds and discounted prices for each market and tier.++Familiarity with Price Lists and volume rules is helpful. See [<u>Set Up Volume Pricing</u>](https://spreecommerce.org/docs/user/how-to/volume-pricing) for a full walkthrough of the volume rule setup.++## Overview++You'll be creating six price lists in total — two tiers for each of the three markets:++| Price List | Market | Volume Rule | Currency |+|---|---|---|---|+| US Volume (21–50 Units) | United States | Min: 21, Max: 50 | USD |+| US Volume (51–100 Units) | United States | Min: 51, Max: 100 | USD |+| Germany Volume (21–50 Units) | Germany | Min: 21, Max: 50 | EUR |+| Germany Volume (51–100 Units) | Germany | Min: 51, Max: 100 | EUR |+| France Volume (21–50 Units) | France | Min: 21, Max: 50 | EUR |+| France Volume (51–100 Units) | France | Min: 51, Max: 100 | EUR |++## 1. Create Volume Price Lists for the US Market++Navigate to **Products → Price Lists** and click **New Price List**.++++Fill in the details for the first US tier:++- **Name** — e.g., `US Volume Pricing (21–50 Units)`+- **Description** — optional (e.g., `Mid-volume USD discount for US market`)+- **Start Date / End Date** — leave blank to apply indefinitely++Click **Create** to open the price list editor.++In the Rules section, set the match logic to **Match All**, then add two rules:++1. Click **Add Rule**, select **Market**, and choose **United States**+2. Click **Add Rule** again, select **Volume**, and set **Min Quantity** to `21` and **Max Quantity** to `50`++++Click **Add Products**, select the products to include, then click **Edit Prices**. Make sure **USD** is selected in the currency switcher and enter the discounted USD prices for this tier.++++Click **Save**, then **Activate** (or **Schedule** if it has a future start date) to make this tier live.++Now repeat to create the second US tier — `US Volume Pricing (51–100 Units)` — with the same Market rule (United States) and a Volume rule set to **Min: 51, Max: 100**. Enter the deeper discounted USD prices and activate.++## 2. Create Volume Price Lists for Germany and France++With the US tiers in place, repeat the same process for Germany and France. For each market you'll create two price lists — one per volume tier.++For each price list:++- Name it clearly, e.g., `Germany Volume Pricing (21–50 Units)` and `Germany Volume Pricing (51–100 Units)`+- Set **Match All** with a **Market** rule targeting the correct market and a **Volume** rule with the appropriate min/max quantities+- When editing prices, make sure **EUR** is selected in the currency switcher and enter the regional EUR discounts for each tier++++Click **Save** and **Activate** for each. Once done, you'll have six active price lists — two tiers for each of the three markets.++<Note>Volume thresholds and discount rates don't need to match across markets. You can set different min/max quantities or different discount levels for each region to reflect local pricing strategies or distribution agreements.</Note>++## 3. Verify on the Storefront++To confirm the tiers are working correctly, test from the storefront across each market.++1. Visit your storefront and switch to the **United States** market.+2. Add a product to the cart, set the quantity to `25`, and confirm the mid-volume USD discount is applied at checkout.+3. Update the quantity to `60` and confirm the deeper USD discount applies.+4. Switch to the **Germany** market, repeat the quantity tests, and confirm the correct EUR discounts appear.+5. Repeat for the **France** market.++If the expected discount is not being applied, check that:++- The price list is set to **Active**+- Both rules (Market and Volume) are present and set to **Match All**+- The quantity in the cart falls within the min–max range of the relevant tier+- The correct currency is set on the prices in the price list editor++## Next Steps++- [<u>Set Up Volume Pricing</u>](https://spreecommerce.org/docs/user/how-to/volume-pricing) — volume discounts without a regional split+- [<u>Set Up Regional Wholesale Pricing</u>](https://spreecommerce.org/docs/user/how-to/regional-wholesale) — combine market and customer group rules for regional wholesale pricing+- [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists) — full reference for rules, match logic, and price editing+- [<u>Markets</u>](https://spreecommerce.org/docs/user/settings/markets) — full reference for configuring Marketsdiff --git a/docs/v5/user/how-to/regional-wholesale.mdx b/docs/v5/user/how-to/regional-wholesale.mdxnew file mode 100644index 0000000000..afca64a744--- /dev/null+++ b/docs/v5/user/how-to/regional-wholesale.mdx@@ -0,0 +1,126 @@+---+title: "Set Up Regional Wholesale Pricing"+description: "Learn how to offer market-specific wholesale pricing to trade customers across multiple regions."+canonical: "https://spreecommerce.org/docs/user/how-to/regional-wholesale"+---++Regional wholesale pricing lets you show different contracted prices to wholesale buyers depending on which market they're shopping in. For example, a US wholesale customer sees USD wholesale prices, while a German wholesale customer sees EUR wholesale prices — and both see prices different from what a standard retail customer would see.++In Spree, you do this by combining a Customer Group rule and a Market rule on each Price List, using **Match All** logic. This means the price list only applies when a customer belongs to the wholesale group *and* is browsing in the correct regional market.++In this guide, we'll set up regional wholesale pricing for a US-based store expanding into Germany and France, with dedicated wholesale tiers for all three markets.++## Prerequisites++Before you start, you should have your products set up with base USD prices. If you're new to multi-currency or wholesale pricing in Spree, it's worth reading these first:++- [<u>Set Up Multi-Currency Pricing</u>](https://spreecommerce.org/docs/user/how-to/multi-currency-pricing) — how to create markets and set base prices per currency+- [<u>Set Up Wholesale Pricing by Customer Group</u>](https://spreecommerce.org/docs/user/how-to/wholesale-pricing) — how to create customer groups and price lists with a Customer Group rule++## 1. Create Markets for Germany and France++Each region needs its own Market before you can target it with a regional price list. If your DE and FR markets are already set up, skip to [Step 2](#2-assign-eur-base-prices-to-your-products).++Navigate to **Settings → Markets** and click **New Market**. Create the Germany market first:++- **Name** — `Germany`+- **Default Country** — `Germany`+- **Currency** — `EUR`+- **Default Locale** — `DE` or `EN`+- **Tax Inclusive** — check this for standard EU VAT-inclusive pricing+- **Default** — leave unchecked++Click **Create**, then repeat to create the France market with **Default Country** set to `France` and **Default Locale** to `FR` or `EN`.++++## 2. Assign EUR Base Prices to Your Products++With EUR markets in place, you'll need to set a base EUR price on every product you want to sell in Germany and France. These base prices are what standard retail customers in those markets will see — your wholesale price lists will override them for wholesale buyers.++Navigate to **Products**, open each product, and use the currency switcher in the **Pricing** or **Variants** section to enter the EUR base price. See [<u>Set Up Multi-Currency Pricing</u>](https://spreecommerce.org/docs/user/how-to/multi-currency-pricing#2-set-eur-prices-on-your-products) for the full walkthrough.++<Warning>Any product without a EUR base price will not appear to customers browsing in the Germany or France markets, including your wholesale buyers. Make sure base EUR prices are set before creating your wholesale price lists.</Warning>++## 3. Create a Wholesale Customer Group++You'll need a single Customer Group to represent all your wholesale buyers across all regions. A single group works here because the regional split is handled by the Market rule on each price list — not by separate groups.++Navigate to **Customers → Customer Groups** and click **New Customer Group**.++++Fill in the details:++- **Name** — e.g., `Wholesale Buyers`+- **Description** — optional (e.g., `Registered trade accounts across all markets`)++<Note>Alternatively, you could set up different Customer Groups for each market.</Note>++Click **Create**, then click **Add Customers** to add your wholesale accounts to the group. Repeat as you onboard new trade customers.++++## 4. Create a Wholesale Price List for Each Market++You'll now create three price lists — one per market. Each will use **Match All** logic with two rules: a Customer Group rule targeting **Wholesale Buyers**, and a Market rule targeting the relevant market. This combination ensures the price list only activates for wholesale customers in that specific region.++### US Wholesale Price List++Navigate to **Products → Price Lists** and click **New Price List**.++- **Name** — e.g., `US Wholesale Pricing`+- **Description** — optional (e.g., `USD wholesale prices for US trade accounts`)+- **Start Date / End Date** — leave blank to apply indefinitely++Click **Create** to open the price list editor.++In the Rules section, set the match logic to **Match All**, then add two rules:++1. Click **Add Rule**, select **Customer Group**, and choose **Wholesale Buyers**+2. Click **Add Rule** again, select **Market**, and choose **United States**++++Click **Add Products**, select the products to include, then click **Edit Prices**. Make sure **USD** is selected in the currency switcher and enter the wholesale USD prices in the **Price** column.++++Click **Save**, then click **Activate** (or **Schedule** if it has a future start date) to make the price list live.++### Germany and France Wholesale Price Lists++Repeat the same process for Germany and France. For each:++- Name them clearly — e.g., `Germany Wholesale Pricing` and `France Wholesale Pricing`+- Set **Match All** with a **Customer Group** rule (Wholesale Buyers) and a **Market** rule targeting the correct market+- When editing prices, make sure **EUR** is selected in the currency switcher and enter the regional EUR wholesale prices++++Click **Save** and **Activate** for each.++<Note>Wholesale prices don't need to be the same across markets. You can set independent EUR prices for Germany and France — for example, to account for local market conditions or distributor agreements.</Note>++## 5. Verify Pricing++To confirm the setup is working correctly, log in to your storefront using a customer account that belongs to the Wholesale Buyers group.++1. Switch to the **United States** market and confirm wholesale USD prices are displayed on your products.+2. Switch to the **Germany** market and confirm wholesale EUR prices are shown.+3. Switch to the **France** market and confirm the France-specific EUR wholesale prices are shown.+4. Log out and repeat the market checks as a guest — you should see standard retail prices across all three markets.++If wholesale prices are not appearing, check that:++- The customer account is added to the **Wholesale Buyers** group+- The price list is set to **Active**+- Both rules (Customer Group and Market) are present and set to **Match All**+- The correct currency is set on the prices in the price list editor++## Next Steps++- [<u>Set Up Wholesale Pricing by Customer Group</u>](https://spreecommerce.org/docs/user/how-to/wholesale-pricing) — wholesale pricing without regional splits+- [<u>Set Up Multi-Region Pricing</u>](https://spreecommerce.org/docs/user/how-to/multi-region-pricing) — regional pricing without a wholesale overlay+- [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists) — full reference for rules, match logic, and price editing+- [<u>Markets</u>](https://spreecommerce.org/docs/user/settings/markets) — full reference for configuring Marketsdiff --git a/docs/v5/user/how-to/schedule-sale-pricing.mdx b/docs/v5/user/how-to/schedule-sale-pricing.mdxnew file mode 100644index 0000000000..b9d26c5f43--- /dev/null+++ b/docs/v5/user/how-to/schedule-sale-pricing.mdx@@ -0,0 +1,113 @@+---+title: "Schedule a Sale"+description: "Learn how to use Price Lists to schedule time-limited sale pricing across your catalog, including market-specific discounts."+canonical: "https://spreecommerce.org/docs/user/how-to/schedule-sale-pricing"+---++Seasonal and promotional pricing events — Black Friday, end-of-season sales, flash discounts — require precise timing. Prices need to go live at the right moment, apply to the right customers, and revert automatically when the window closes. Doing this manually is error-prone, and scrambling to update prices or remove a promotion code at midnight is not how you want to spend a Friday evening.++Price Lists in Spree are designed for exactly this. You build the sale in advance — set the discounted prices, define which markets or customer groups it applies to, and attach a start and end date. Spree schedules the activation automatically. When the sale starts, the discounted prices appear on product pages for the right customers. When it ends, base prices return — no manual intervention needed.++This guide walks through a Black Friday scenario: one set of discounts for US customers and another for EU customers, starting Friday midnight and ending Monday. The same approach works for any time-limited pricing event, whether it's a single market or several.++## Price Lists vs. Promotions++Both tools can reduce what a customer pays, but they work differently and suit different situations.++**Promotions** apply a discount at checkout — a percentage off the order total, a fixed amount off, free shipping, or a coupon code. They're well suited to straightforward sitewide offers (e.g., 15% off everything with a code) or one-time deals. However, if you want to apply *different discounts to different products* — say, 20% off one category, 10% off another, 15% off one set of products, 25% off another set — you'd need a separate promotion for each variation. Promotions also don't change the price shown on the product page; the discount appears at checkout.++**Price Lists** let you set the actual sale price for each product individually. One price list can cover your entire catalog — add as many products as you need and set each one's sale price directly. The discounted price shows on the product page, not just at checkout, and the list activates and deactivates automatically on schedule. This makes Price Lists the better tool for sitewide or catalog-wide sales where you want the reduced price to be visible from the moment a customer lands on a product.++<Note>For a simple sitewide percentage discount with a code, promotions may be quicker to set up. Price Lists shine when you need scale, market-specific rates, or per-product control over the discounted price.</Note>++## Prerequisites++Before you start, make sure:++- Your products are set up with base prices in both USD and EUR+- You have a **United States** market and an **EU** (or equivalent European) market configured. See [<u>Settings → Markets</u>](https://spreecommerce.org/docs/user/settings/markets) for setup instructions.+- You're familiar with how Price Lists work. See [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists) for a full reference.++## 1. Create the US Black Friday Price List++Navigate to **Products → Price Lists** in the admin dashboard and click **New Price List**.++++Fill in the details:++- **Name** — e.g., `Black Friday — US (USD)`+- **Description** — optional (e.g., `Sale discounts for US customers, Black Friday weekend`)+- **Start Date** — set to the date and time your sale begins (e.g., Friday, 00:00)+- **End Date** — set to the date and time your sale ends (e.g., Monday, 23:59)++Click **Create** to open the price list editor.++### Add a Market Rule++In the price list editor, click **Add Rule** and select **Market** from the rule type dropdown. Select **United States** from the options.++++This ensures the sale pricing only applies to customers shopping in the US market.++### Add Products and Set Sale Prices++Click **Add Products** to open the product selector. Select the products you want to include in the sale and click **Add Selected**.++Once the products appear in the list, click **Edit Prices**. Make sure **USD** is selected in the currency switcher, then enter the discounted price for each product in the **Price** column.++++<Note>The price editor works like a spreadsheet — you can highlight multiple price fields and paste values in bulk to speed up entry across a large catalog.</Note>++Click **Save** to apply the prices.++## 2. Create the EU Black Friday Price List++Click **New Price List** again and create a second list for EU customers:++- **Name** — e.g., `Black Friday — EU (EUR)`+- **Description** — optional (e.g., `Sale discounts for EU customers, Black Friday weekend`)+- **Start Date / End Date** — same window as the US list++Click **Create**, then in the price list editor:++1. Click **Add Rule**, select **Market**, and choose your EU market+2. Click **Add Products** and add the same products+3. Click **Edit Prices**, make sure **EUR** is selected++++Click **Save**.++## 3. Schedule Both Price Lists++With both price lists configured, go back to each one and click **Schedule** in the top right corner.++++<Note>Because both price lists have a future start date, the button reads **Schedule** rather than **Activate**. Spree will automatically activate them at the start date and deactivate them at the end date — no manual intervention needed.</Note>++Both price lists will now appear as **Scheduled** in your Price Lists overview. On Black Friday, they activate automatically. On Monday at midnight, they switch off and your base prices return.++## 4. Verify++Once the sale is live (or to test in advance by temporarily setting the start date to now), confirm the pricing is applying correctly:++1. Visit your storefront in the **United States** market as a guest — product pages should show the discounted USD prices.+2. Switch to your **EU** market — product pages should show the discounted EUR prices.+3. Switch to any market not covered by either price list — standard base prices should appear.++If the sale price isn't showing, check that:++- The price list status is **Active** (or **Scheduled**, if the start date hasn't passed yet)+- The product has been added to the price list+- The Market rule is correctly set to the intended market+- The correct currency is selected in the price editor++## Next Steps++- [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists) — full reference for rules, scheduling, and price editing+- [<u>Set Up Multi-Region Pricing</u>](https://spreecommerce.org/docs/user/how-to/multi-region-pricing) — apply different prices per market on a permanent basis+- [<u>Set Up Wholesale Pricing</u>](https://spreecommerce.org/docs/user/how-to/wholesale-pricing) — combine market and customer group rules for B2B pricingdiff --git a/docs/v5/user/how-to/volume-pricing.mdx b/docs/v5/user/how-to/volume-pricing.mdxnew file mode 100644index 0000000000..9fe78955ff--- /dev/null+++ b/docs/v5/user/how-to/volume-pricing.mdx@@ -0,0 +1,93 @@+---+title: "Set Up Volume Pricing"+description: "Learn how to offer tiered discounts based on order quantity using Price Lists in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/how-to/volume-pricing"+---++Volume pricing lets you automatically offer lower prices when customers order larger quantities. A common use case is rewarding bulk buyers — for example, offering one price for orders of 21–50 units and a deeper discount for orders of 51–100 units.++In Spree, you set this up using Price Lists with a Volume rule. Each pricing tier gets its own price list, and Spree applies the correct price automatically based on the quantity in the customer's order.++In this guide, we'll set up two tiers: a mid-volume tier (21–50 units) and a high-volume tier (51–100 units).++<Note>This guide focuses on volume-based pricing. If you need to combine volume pricing with customer group or regional rules — for example, offering wholesale volume discounts only to registered trade customers — see [<u>Set Up Wholesale Pricing by Customer Group</u>](https://spreecommerce.org/docs/user/how-to/wholesale-pricing) instead.</Note>++## Prerequisites++Before you start, you should have your products uploaded and set up with base prices. Volume pricing overrides those base prices when the quantity conditions are met — products without a base price will not be affected.++Familiarity with how Price Lists work is helpful. See [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists) for a full reference.++## 1. Create the First Volume Price List (21–50 Units)++To create price list, navigate to **Products → Price Lists** in the admin dashboard and click **New Price List**.++++Fill in the details for the first tier:++- **Name** — e.g., `Volume Pricing (21–50 Units)`+- **Description** — optional (e.g., `Mid-volume discount — applies when ordering between 21 and 50 units`)+- **Start Date / End Date** — leave blank if this pricing should apply indefinitely++Click **Create** to open the price list editor.++### Add a Volume Rule++In the price list editor, click **Add Rule** and select **Volume** from the rule type dropdown.++++Set the quantity range for this tier:++- **Min Quantity** — `21`+- **Max Quantity** — `50`++This ensures the price list only activates when a customer's order quantity falls within that range.++### Add Products and Set Prices++Click **Add Products** to open the product selector. Search for and select the products you want to include in this tier, then click **Add Selected**.++Once the products appear in the list, click **Edit Prices** to open the price editor. Enter the discounted price for each product in the **Price** column.++++Click **Save** to apply the prices, then click **Activate** (or **Schedule** if it has a future start date) to make the price list live.++## 2. Create the Second Volume Price List (51–100 Units)++Repeat the same process for the higher-volume tier. Click **New Price List** and fill in the details:++- **Name** — e.g., `Volume Pricing (51–100 Units)`+- **Description** — optional (e.g., `High-volume discount — applies when ordering between 51 and 100 units`)++In the price list editor, add a **Volume** rule and set:++- **Min Quantity** — `51`+- **Max Quantity** — `100`++Add the same products and enter the deeper discounted prices for this tier, then click **Save** and **Activate**.++<Note>If you want pricing to apply for orders above 100 units with no upper limit, leave the **Max Quantity** field blank on that price list.</Note>++## 3. Verify on the Storefront++To confirm your volume tiers are working correctly, test by adding products to the cart in quantities that fall within each tier.++1. Visit your storefront and add a product to the cart.+2. Set the quantity to a value within the first tier (e.g., `25`) and confirm the mid-volume price is applied at checkout.+3. Update the quantity to a value within the second tier (e.g., `60`) and confirm the deeper discount is applied.+4. Set the quantity below the first tier threshold (e.g., `5`) and confirm the standard base price is shown.++If the expected price is not being applied, check that:++- The product has been added to the correct price list+- The price list is set to **Active**+- The Volume rule min and max quantities are correctly set and do not overlap between tiers++## Next Steps++- [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists) — full reference for rules, product selection, and price editing+- [<u>Set Up Wholesale Pricing by Customer Group</u>](https://spreecommerce.org/docs/user/how-to/wholesale-pricing) — offer tiered pricing to specific customer segments+- [<u>Set Up Multi-Region Pricing</u>](https://spreecommerce.org/docs/user/how-to/multi-region-pricing) — combine regional and volume rules for market-specific discountsdiff --git a/docs/v5/user/how-to/wholesale-pricing.mdx b/docs/v5/user/how-to/wholesale-pricing.mdxnew file mode 100644index 0000000000..3d996a55e6--- /dev/null+++ b/docs/v5/user/how-to/wholesale-pricing.mdx@@ -0,0 +1,96 @@+---+title: "Set Up Wholesale Pricing"+description: "Learn how to offer wholesale pricing to specific customer groups using Price Lists in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/how-to/wholesale-pricing"+---++Wholesale pricing lets you show different prices to different types of buyers — for example, trade customers or registered wholesalers see their negotiated prices, while regular customers continue to see standard retail prices. Because pricing is tied to the customer's account, there's no need for separate storefronts or manual price management.++In Spree, you do this by creating a Customer Group for your wholesale buyers, then creating a Price List with a Customer Group rule that targets it. You can create as many price lists as you need — one per wholesaler or tier — each with its own pricing and conditions.++<Note>This approach also enables a combined B2C and B2B setup on a single storefront: retail customers see base prices by default, while logged-in wholesale customers automatically see their contracted pricing. No separate store or login portal required.</Note>++## Prerequisites++Before you start, you should have your products set up with base prices. Wholesale pricing overrides those base prices for customers in the relevant group — all other customers continue to see the standard price.++Familiarity with how Price Lists work is helpful. See [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists) for a full reference.++## 1. Create a Customer Group++First, you'll need a Customer Group to represent your wholesale buyers. If you already have a suitable group set up, you can skip to [Step 2](#2-create-a-wholesale-price-list).++Navigate to **Customers → Customer Groups** in the admin dashboard and click **New Customer Group**.++++Fill in the details:++- **Name** — e.g., `Wholesale Buyers` or a specific account name if this group is for a single wholesaler+- **Description** — optional, but useful for other admins (e.g., `Registered trade accounts with negotiated wholesale pricing`)++Click **Create** to save the group.++## 2. Add Customers to the Group++Once the group is created, you'll be taken to its detail view. Click **Add Customers** to open the customer selector panel.++++Search for the customers you want to include, check the boxes next to their names, and click **Add Selected**. The customers will now appear in the group.++++Repeat this process whenever you onboard a new wholesale account — simply add them to the relevant group and their pricing will apply automatically on their next login.++## 3. Create a Wholesale Price List++With your customer group in place, navigate to **Products → Price Lists** and click **New Price List**.++++Fill in the details:++- **Name** — e.g., `Wholesale Buyers Pricing`+- **Description** — optional (e.g., `Standard wholesale pricing for registered trade accounts`)+- **Start Date / End Date** — leave blank if this pricing should apply indefinitely++Click **Create** to open the price list editor.++### Add a Customer Group Rule++In the price list editor, click **Add Rule** and select **Customer Group** from the rule type dropdown. Select **Wholesale Buyers** from the options.++++This ensures the price list only applies to logged-in customers who are members of that group.++### Add Products and Set Prices++Click **Add Products** to open the product selector. Search for and select the products you want to include in this price list, then click **Add Selected**.++Once the products appear in the list, click **Edit Prices** to open the price editor. Enter the wholesale price for each product in the **Price** column.++++Click **Save** to apply the prices, then click **Activate** (or **Schedule** if it has a future start date) to make the price list live.++<Note>If you work with multiple wholesalers on different negotiated terms, create a separate Customer Group and Price List for each. For example, a `Distributor A` group and `Distributor A Pricing` list, and a `Distributor B` group with its own list. Each wholesaler's customers will only ever see their own contracted prices.</Note>++## 4. Verify Pricing++To confirm the setup is working correctly, log in to your storefront using a customer account that belongs to the Wholesale Buyers group and browse to a product you included in the price list. The wholesale price should be displayed instead of the standard retail price.++If the expected price is not showing, check that:++- The customer's account has been added to the correct Customer Group+- The product has been added to the price list+- The price list is set to **Active**+- The Customer Group rule is correctly configured++## Next Steps++- [<u>Customer Groups</u>](https://spreecommerce.org/docs/user/customers/customer-groups) — full reference for creating and managing customer groups+- [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists) — full reference for rules, product selection, and price editing+- [<u>Set Up Volume Pricing</u>](https://spreecommerce.org/docs/user/how-to/volume-pricing) — add quantity-based tiers on top of your wholesale pricing+- [<u>Set Up Multi-Region Pricing</u>](https://spreecommerce.org/docs/user/how-to/multi-region-pricing) — apply regional price variations within a customer groupdiff --git a/docs/v5/user/manage-products/bulk-product-operations.mdx b/docs/v5/user/manage-products/bulk-product-operations.mdxnew file mode 100644index 0000000000..a74407adb2--- /dev/null+++ b/docs/v5/user/manage-products/bulk-product-operations.mdx@@ -0,0 +1,87 @@+---+title: "Bulk Product Operations"+description: "Learn how to perform bulk product operations in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/manage-products/bulk-product-operations"+---++Managing a large product catalog doesn’t mean you need to edit each product one by one. Spree’s bulk operations make it easy to update multiple products at once, saving you time and reducing repetitive work.++Bulk operations can be used to:++- Update product statuses+- Add/remove taxons+- Add/remove tags++<Note>+ Bulk operations can be used in combination with product search and filters, for example, to quickly tag all products in a specific taxon.+</Note>++## How to Perform Bulk Operations++Navigate to the **Products** tab in the admin dashboard.++++Select one or more products by checking the boxes on the left-hand side of the list.++Once selected, the bulk actions menu will appear at the bottom of the page.++++The menu will show how many products are selected and present several action options.++## Status Updates++++The following actions are available directly in the bulk menu:++- **Set as Active**: Marks selected products as active and visible on the storefront.+- **Set as Draft**: Moves selected products to draft status, making them hidden from the storefront.+- **Set as Archived**: Archives the selected products, removing them from storefront view while keeping them in the admin (accessed in the three-dot menu).++## Taxon Management++These options, accessible in the three-dot menu, let you bulk-manage product categories and collections:++### Add to Taxons++++Using the **Add to taxons** operation, you can assign one or more taxons to the selected products.++Simply select taxons from the dropdown list or start typing to narrow results.++### Remove from Taxons++++Similar to above, you can use the **Remove from taxons** operation to remove specific taxons from selected products.++Multiple taxons can be removed at once using the same interface.++## Tag Management++You can also quickly assign or unassign tags across multiple products:++### Add Tags++++Using the **Add tags** operation, you can apply one or more tags to all selected products at once.++Select tags from the dropdown list or create new ones on the fly directly within the interface.++### Remove Tags++++The **Remove tags** operation allows you to remove selected tags from all chosen products.++As before, multiple tags can be removed at once.++## Saving Changes++++After selecting and confirming your desired operation, always click **Save** in the bottom right corner of the modal to apply your changes.\ No newline at end of filediff --git a/docs/v5/user/manage-products/export-products.mdx b/docs/v5/user/manage-products/export-products.mdxnew file mode 100644index 0000000000..dbaa43002a--- /dev/null+++ b/docs/v5/user/manage-products/export-products.mdx@@ -0,0 +1,30 @@+---+title: "Export Products"+description: "Learn how to export your product catalog in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/manage-products/export-products"+---++Exporting your product catalog can be useful for a variety of tasks, such as reviewing product data in bulk, backing up product information, or syncing catalog details with external systems like ERPs or reporting tools.++## How to Export Your Product Catalog++To export your product catalog, navigate to the **Products** tab of the admin dashboard.++++Click on **Export** in the top right corner.++++This opens an export modal that gives you two options to choose from:++- **Filtered Records**: Export only filtered records matching the search criteria+- **All**: Export all records (can be slow for large datasets)++<Warning>+ If you plan to export a subset of your product catalog, make sure to apply the appropriate filters before clicking **Export**.+</Warning>++Once you’ve made your selection, click **Export** in the modal, and a link to download the file will be sent to the email address associated with your user account.++<Note>If your store sells in multiple currencies, the exported file will automatically include additional price-only rows for each currency. See [<u>Multi-Currency Import/Export</u>](https://spreecommerce.org/docs/user/manage-products/multi-currency-import-export) for details on how these rows work.</Note>diff --git a/docs/v5/user/manage-products/import-products.mdx b/docs/v5/user/manage-products/import-products.mdxnew file mode 100644index 0000000000..7580a5cb3b--- /dev/null+++ b/docs/v5/user/manage-products/import-products.mdx@@ -0,0 +1,87 @@+---+title: "Import Products"+description: "How to import products files in the Spree Commerce dashboard."+canonical: "https://spreecommerce.org/docs/user/manage-products/import-products"+---++Adding products one at a time can be time consuming - especially when you're dealing with hundreds or thousands of SKUs.++Spree’s CSV importer allows you to upload products in bulk using a pre-formatted CSV file, dramatically reducing the time required to launch or scale your catalog.++Need an example? Please refer to [<u>Product Import File Template</u>](https://spreecommerce.org/docs/user/manage-products/product-import-file-template) to download a template and see a list of internal fields.++<Note>Your product file does not need to exactly match the import template. Thanks to the field mapping step, you can manually match each column to the appropriate internal field during import (see Step 2 below).</Note>++## How to Import Products++To get started, navigate to the Products tab of the admin dashboard.++++Click **Import** in the top right corner. This will open a side panel where you can begin the import process.++++From here, simply follow these steps to import your product catalog:++### Step 1: Upload a Product File++++First, you’ll need to upload the file you wish to import. Either **drag-and-drop the file** into the box or select a file from your computer by clicking **browse files**.++<Note>The importer supports both single and multi-variant products - just follow the multi-variant format in the [<u>Product File Import Template</u>](https://spreecommerce.org/docs/user/manage-products/product-import-file-template).</Note>++If successful, the UI will indicate that the upload was completed:++++<Note>Double-check for any formatting issues, data type mismatches, and duplicates before uploading.</Note>++#### Select a Delimiter++++Before processing the file, you need to select which delimiter separates values in your file:++- , (comma) - most common for CSVs+- | (pipe)+- ; (semicolon)+- \\t (tab)++Once the file has been uploaded and the correct delimiter has been selected, click **Create** at the bottom of the side panel to continue to Step 2.++### Step 2: Map Fields and Submit++++With the file uploaded, you’ll now be prompted to map your file’s columns to Spree’s internal fields.++Spree will try to match fields automatically when names are identical (or very similar), but you can manually select destination fields from the dropdowns on the right-hand side column for any unmatched, or incorrectly mapped fields.++Once satisfied, click **Continue** in the bottom-right corner to submit the file for import.++### Step 3: Monitor Import Status++++After submitting the file, you'll be redirected to a processing screen where you can monitor the progress of the import. All that’s left to do is wait until the import has finished processing++<Note>If there are any errors in your file (e.g., missing fields, duplicate values), the processing screen will indicate the error with an error message on the affected row.</Note>++## Update Products in Bulk++You can also use the product importer to update existing products in your catalog.++To do so:++1. [<u>Export your product catalog</u>](https://spreecommerce.org/docs/user/manage-products/export-products) from the Products tab+2. Make any necessary changes directly in the file+3. Re-import the updated file through the product importer++<Warning>When updating products in bulk, make sure to keep the slug exactly the same for each existing product. The slug is the unique identifier used during import - changing it will cause Spree to treat the row as a new product and create a duplicate record.</Warning>++This is the safest and most efficient way to make large-scale updates to product data such as pricing, descriptions, inventory, or metafields.++<Note>If your store sells in multiple currencies, your exported file will include additional price-only rows for each currency. See [<u>Multi-Currency Import/Export</u>](https://spreecommerce.org/docs/user/manage-products/multi-currency-import-export) for details on how these rows work.</Note>+diff --git a/docs/v5/user/manage-products/multi-currency-import-export.mdx b/docs/v5/user/manage-products/multi-currency-import-export.mdxnew file mode 100644index 0000000000..5ef578fd80--- /dev/null+++ b/docs/v5/user/manage-products/multi-currency-import-export.mdx@@ -0,0 +1,68 @@+---+title: "Multi-Currency Import/Export"+description: "Learn how to import and export product prices across multiple currencies in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/manage-products/multi-currency-import-export"+---++If your store is configured to sell in more than one currency, Spree's product import/export automatically handles pricing for each currency in a single file. This makes it straightforward to review, update, or set prices across all your markets without needing separate exports for each currency.++<Note>Multi-currency import/export relies on your Markets configuration. Each currency in the export corresponds to a market you've set up in your store. See [<u>Settings → Markets</u>](https://spreecommerce.org/docs/user/settings/markets) for more details.</Note>++## How It Works++When you export your product catalog, Spree generates one row per product variant for your default currency — exactly as it always has. For each additional currency your store supports, Spree adds an extra row for each variant containing only the pricing information for that currency.++These additional rows are called **price-only rows**. They contain a smaller set of columns:++- **SKU** - Identifies which variant the price belongs to+- **Slug** - Identifies which product the variant belongs to+- **Price** - The price in the specified currency+- **Compare At Price** - The original/crossed-out price, if applicable+- **Currency** - The currency code for this row (e.g., `EUR`, `GBP`)++All other product fields (name, description, taxons, metafields, etc.) are left blank in price-only rows — they're intentionally omitted because those fields are already handled by the primary row.++## Exporting Multi-Currency Prices++The export process is the same as a standard product export. Navigate to the **Products** tab and click **Export** in the top-right corner.++++Choose to export **Filtered Records** or **All**, then click **Export**. A download link will be sent to your admin email address.++When you open the file, you'll see your standard product rows followed by price-only rows for each additional currency. For example, a store selling in USD (default) and EUR would look something like this:++| SKU | Slug | Name | Price | Currency | ... |+|---|---|---|---|---|---|+| SHIRT-SM | blue-shirt | Blue Shirt | 29.99 | USD | ... |+| SHIRT-MD | blue-shirt | Blue Shirt | 34.99 | USD | ... |+| SHIRT-SM | blue-shirt | | 27.99 | EUR | |+| SHIRT-MD | blue-shirt | | 31.99 | EUR | |++The blank fields in the EUR rows are expected — only the pricing columns matter for those rows.++## Importing Multi-Currency Prices++You can update prices across currencies by editing the exported file and re-importing it through the standard product importer.++<Warning>When editing price-only rows, do not change the SKU or slug values. These are used to match each row to the correct product variant — changing them will prevent the import from updating the right records.</Warning>++To import your updated file, navigate to the **Products** tab and click **Import** in the top-right corner. This opens the import side panel.++++1. Drag and drop your CSV file into the upload area, or click **browse files** to select it from your computer.+2. Select the correct delimiter used in your file (comma, pipe, semicolon, or tab).+3. Click **Create** to proceed to the field mapping step.+4. Review the field mapping and adjust any columns that weren't matched automatically, then click **Continue** to submit.++Spree will automatically detect which rows are full product rows and which are price-only rows. For price-only rows, it will update only the pricing data for the specified currency — it won't overwrite your product descriptions, taxons, or metafields.++<Note>You can import pricing updates for a single currency without including rows for other currencies. Just remove any rows you don't want to update before importing.</Note>++## Next Steps++- [<u>Import Products</u>](https://spreecommerce.org/docs/user/manage-products/import-products) — Full guide to importing product data+- [<u>Export Products</u>](https://spreecommerce.org/docs/user/manage-products/export-products) — Full guide to exporting your product catalog+- [<u>Settings → Markets</u>](https://spreecommerce.org/docs/user/settings/markets) — Configure markets and currencies for your store+- [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists) — Set customer- or volume-specific pricing on top of your base pricesdiff --git a/docs/v5/user/manage-products/price-lists.mdx b/docs/v5/user/manage-products/price-lists.mdxnew file mode 100644index 0000000000..e197a47662--- /dev/null+++ b/docs/v5/user/manage-products/price-lists.mdx@@ -0,0 +1,92 @@+---+title: "Price Lists"+description: "Learn how to set up volume pricing, user-specific pricing, and more in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/manage-products/price-lists"+---++import { Since } from '/snippets/since.mdx';++<Since version="5.3" />++Price lists are a powerful tool for managing customer-specific pricing strategies - essential for industries like B2B, wholesale, and marketplaces. They let you offer different prices to different customer segments based on conditions like location, quantity, or account status, without needing to duplicate product records or use heavy customizations.++With Spree’s native support for price lists, you can create and manage custom pricing logic directly in the admin dashboard - no development required.++## Create a Price List++To get started, navigate to **Products → Price Lists** in the admin dashboard.++++Here, you’ll see an overview of all active and inactive price lists. Click **New Price List** in the top right corner to open the price list creation form.++++Fill in the following fields:++- **Name** - Internal name for the price list (displayed in the admin).+- **Description (optional)** - Notes or context for other admins.+- **Start Date** and **End Date** - Defines when the price list should be active.+ - If not set, the price list will take effect immediately and it will never expire++Once you’ve completed the above, click **Create** to proceed.++## Configure a Price List++++Once created, you’ll be redirected to the price list edit form, where you can define rules for when the price list should apply, add products to be included in the price list, and set the modified prices of those products.++### Add Rules++++You can add multiple rules with Match Any or Match All logic.++Available Rule Types:++- **User** - Apply pricing only for specific users.+- **Customer Group** - Apply pricing to a specific customer group.+- **Market** - Apply pricing to customers shopping in a specific market.+- **Volume** - Apply pricing when order quantity falls within a min–max range.+- **Zone** - Apply pricing to customers in a specific tax/shipping zone.++To add a rule, simply click **Add Rule**, select a rule type, and configure its criteria.++### Add Products++++Next, you’ll need to add some products to the price list. To do so, click **Add Products** in Products subsection to open the product selector side panel.++++Search for products by name or SKU, select one or more products and click **Add Selected** to add them to the price list.++The selected products will now appear in the product list.++### Setting Prices++To define custom prices for the list, click **Edit Prices** in the top right of the product list to open the price edit form.++++Select which currency you'd like to update prices for, and update the values in the **Price** column and optionally in the **Compare At** column.++<Note>You can highlight multiple fields and copy + paste like you would in a spreadsheet.</Note>++++Once you’ve finished entering the custom prices, click **Save** to apply your changes.++## Activating the Price List++Once everything is configured, go back to the price list editor, and click **Activate** in the top right corner.++++The price list will now take effect immediately for any user or order that matches the configured rules.++You can deactivate the price list at any time by clicking the **Deactivate** button.++<Note>If you set a start date for the price list, the **Activate/Deactivate** button will instead say **Schedule/Unschedule**.</Note>diff --git a/docs/v5/user/manage-products/product-import-file-template.mdx b/docs/v5/user/manage-products/product-import-file-template.mdxnew file mode 100644index 0000000000..54bff3befa--- /dev/null+++ b/docs/v5/user/manage-products/product-import-file-template.mdx@@ -0,0 +1,54 @@+---+title: "Import File Template"+description: "Download a product import file template for Spree Commerce open-source"+canonical: "https://spreecommerce.org/docs/user/manage-products/product-import-file-template"+---++Below is a list of all the product fields that can be imported via CSV (required fields in bold).++For an example of **how to structure multi-variant products**, please download this [product import file template](https://raw.githubusercontent.com/spree/spree/refs/heads/main/docs/downloads/product_import_file_template.csv).++<Note>You don’t need to follow the field naming conventions in this template exactly. Field names can be mapped manually during the import process.</Note>++<Warning>The **slug** field acts as the unique identifier for the product in Spree - no two products can share the same slug. When updating products via CSV import, the slug must exactly match an existing record to avoid creating duplicates.</Warning>++| Field | Description |+| ----------------------- | ------------------------------------------------------------------------------------------- |+| **sku** | A unique alphanumeric code used to identify variants |+| **name** | The name of the product |+| **slug** | Sets the URL path of the product (e.g. yourstore.com/products/slug) |+| status | The status of the product, e.g., Active, Draft, Archived |+| description | The product description |+| meta_title | If not set, Name will be used in search engine listings |+| meta_description | If not set, Description will be used in search engine listings |+| meta_keywords | Can improve your website's visibility, attract more relevant traffic |+| tags | Tags that should be added to the product |+| price | The price for the product/variant to be paid by the customer |+| compare_at_price | The non-marked-down price of the product being sold |+| currency | The currency in which the price should be imported |+| width | Width of the product/variant |+| height | Height of the product/variant |+| depth | Depth of the product/variant |+| dimensions_unit | The unit of measurement used for the dimensions (in, ft, cm, mm) |+| weight | Weight of the product/variant |+| weight_unit | The unit of measurement used for weight (oz, lbs, g, kg) |+| available_on | When the product should be made available for purchase |+| discontinue_on | When the product should be discontinued and hidden from the storefront |+| track_inventory | Whether or not you track inventory levels for the product (TRUE/FALSE) |+| inventory_count | The stock quantity of the product/variant |+| inventory_backorderable | Whether the product can be ordered when out of stock |+| tax_category | The tax category the product should be assigned, e.g., Default, Non-taxable |+| shipping_category | The shipping category the product should be assigned, e.g., Default, Digital |+| image1_src | A link to the primary image product/variant image |+| image2_src | A link to the second product/variant image |+| image3_src | A link to the third product/variant image |+| option1_name | The name of the 1st [product option](https://spreecommerce.org/docs/user/manage-products/product-options)|+| option1_value | The value of the 1st product option |+| option2_name | The name of the 2nd product option |+| option2_value | The value of the 2nd product option |+| option3_name | The name of the 3rd product option |+| option3_value | The value of the 3rd product option |+| category1 | The 1st [category](https://spreecommerce.org/docs/user/manage-products/product-taxonomies) to which the product should be assigned|+| category2 | The 2nd category to which the product should be assigned |+| category3 | The 3rd category to which the product should be assigned |+| metafield.namespace.key | The value for the product metafield [namespace.key](https://spreecommerce.org/docs/user/settings/metafields)|diff --git a/docs/v5/user/manage-products/product-metafields.mdx b/docs/v5/user/manage-products/product-metafields.mdxnew file mode 100644index 0000000000..7188b6cf42--- /dev/null+++ b/docs/v5/user/manage-products/product-metafields.mdx@@ -0,0 +1,243 @@+---+title: "Product Metafields"+description: "Learn how to use product metafields in Spree Commerce to enrich your product data."+canonical: "https://spreecommerce.org/docs/user/manage-products/product-metafields"+---++Product Metafields allow you to add custom attributes to products beyond the default fields included in Spree. Whether you want to display additional product specifications on the storefront, store internal merchandising notes, or support advanced integrations, metafields give you complete flexibility directly from the admin dashboard.++Unlike legacy product properties, metafields are structured, scalable, and work seamlessly with imports, APIs, and storefront display settings.++## Why Use Product Metafields?++Product metafields are ideal when you need to:++- Add **technical specifications** (e.g., voltage, dimensions, fabric composition)+- Display **care instructions**+- Highlight **sustainability certifications**+- Store **supplier or internal notes**+- Add **regulatory information**+- Include **SEO enhancements**+- Attach **structured product data**+- Power custom storefront sections+- Support third-party integrations++Because metafields can be created and managed entirely from the dashboard, they reduce development time and eliminate the need for database changes or code deployments.++## How to Create a Product Metafield++To create a new product metafield, navigate to **Settings → Metafield Definitions**.++++Click **New Metafield Definition** to open the metafield creation form.++++Complete the form fields as described below.++## **Metafield Definition Fields**++### **Name**++The display name shown in the admin panel and (optionally) on the storefront.\+Example:++- Material+- Care Instructions+- Sustainability Rating++### **Namespace**++Used to group metafields and avoid naming conflicts.++- We recommend using something like **custom** for merchant-defined product fields.+- Avoid using reserved model names like **product**, **variant**, or **order**.++### **Key**++The unique identifier for the metafield (combined with the namespace).++Example:++- **custom.material**+- **custom.care_instructions**+- **custom.sustainability_score**++### **Resource**++For product metafields, select **Product**.++To learn more about creating metafields for other resources, see [<u>Metafields</u>](https://spreecommerce.org/docs/user/settings/metafields).++## **Choosing the Right Data Type**++Each metafield must have a type. Selecting the appropriate type ensures your data is structured correctly.++### **Short Text**++Single-line text values.++Examples:++- “Denim”+- “Made in Italy”+- “BPA Free”++### **Long Text**++Multi-line text without formatting.++Examples:++- Care instructions+- Ingredient lists+- Warranty information++### **Rich Text**++Formatted content with styling options.++Examples:++- Marketing descriptions+- Detailed sustainability breakdowns+- Compliance disclaimers++### **Number**++Numeric values.++Examples:++- 4.8 (average rating)+- 32 (waist size)+- 750 (capacity in ml)++### **Boolean**++True/false values.++Examples:++- Is this product eco-friendly?+- Is this item fragile?+- Limited edition?++### **JSON**++Structured data or multiple related values.++Examples:++- Technical specifications object+- Nutritional breakdown+- Multi-attribute certification data++## Display Settings++Choose where the metafield should appear:++- **Admin Only** - Internal use (e.g., supplier notes, internal margin classification)+- **Admin & Storefront** - Visible to customers on product pages++If displayed on the storefront, metafields can be used within your theme to enhance the Product Detail Page (PDP).++## Adding Product Metafield Values++Once the definition is created, you can assign values to individual products.++### Adding Values Individually++++To add metafield values for individual products:++1. Navigate to **Products**+2. Open the product you want to update+3. Click the **three-dot menu** in the top-right corner+4. Select **Metafields** to open the metafields form+5. Enter the desired values+6. Click **Save**++This method is ideal for updating a small number of products.++### Updating Product Metafields in Bulk++You can also import metafields via CSV.++#### Step 1: Add a Column to the product CSV file++Use this format:++**metafield.namespace.key**++Example:++- **metafield.custom.material**+- **metafield.custom.care_instructions**+- **metafield.custom.sustainability_score**++#### Step 2: Add Values Per Product Row++Fill in the values for each product.++#### Step 3: Import the File++- Upload during a new product import **or**+- Export your existing catalog, update it, and reimport with the newly added columns to apply changes++This is especially useful when enriching large product catalogs.++Please refer to the following support articles for more information about product imports:++- [<u>Import Product</u>](https://spreecommerce.org/docs/user/manage-products/import-products)+- [<u>Product Import Template</u>](https://spreecommerce.org/docs/user/manage-products/product-import-file-template)++## Real-World Product Metafield Examples++Here are some practical examples of how merchants use product metafields:++### Apparel++- Material: “100% Organic Cotton”+- Care Instructions: “Machine wash cold, tumble dry low”+- Fit Type: “Slim Fit”+- Fabric Weight (gsm): 180++### Electronics++- Battery Life: 12 (hours)+- Warranty Period: 24 (months)+- Waterproof: true+- Voltage: 110–240V++### Food & Supplements++- Allergens: “Contains nuts”+- Ingredients: Long text field+- Nutritional Info: JSON structure+- Expiration Period: 18 (months)++### Furniture++- Assembly Required: true+- Weight Capacity: 250 (lbs)+- Material Finish: “Matte Walnut”+- Care Instructions: Rich text++### B2B Use Cases++- Internal Margin Tier (Admin Only)+- Supplier SKU+- Minimum Order Quantity+- Packaging Type+- Compliance Classification++## Replacing Product Properties++Product Properties are no longer supported in the latest version of Spree. Product Metafields provide a more flexible, scalable, and structured solution for managing custom product attributes.++If you previously relied on properties for product enrichment, metafields are now the recommended approach.++Product metafields give you the flexibility to tailor your product data model to your business - without relying on developers - while keeping your catalog structured, scalable, and integration-ready.diff --git a/docs/v5/user/manage-products/product-options.mdx b/docs/v5/user/manage-products/product-options.mdxnew file mode 100644index 0000000000..1a2842a2ac--- /dev/null+++ b/docs/v5/user/manage-products/product-options.mdx@@ -0,0 +1,113 @@+---+title: "Product Options"+description: "How to manage product options in the Spree Commerce open-source dashboard"+canonical: "https://spreecommerce.org/docs/user/manage-products/product-options"+---++Product options define customizable product attributes (such as size, color, or material) that generate selectable variants for customers.++They improve the shopping experience by helping users quickly find and choose the desired variant and often serve as filters on the PLP.++In the backend, they consolidate inventory tracking by grouping all variants under a single product record.++To manage Options, navigate to **Products → Options** in the admin dashboard++++Here you’ll see a list of all the Options currently added to your store.++## Add a New Option++To add a new Option, click **New Option Type** in the top right corner.++This will redirect you to the Option creation form:++++Here you must fill in two sections to define your new Option:++### General Information++++In this section you can set the display name and the internal name for the Option Type. If you don’t set an internal name, the presentation name will be used.++You can also select whether or not you want this Option to be filterable on product listing pages by checking the **Filterable** box++When an option type is set to Filterable, your storefront visitors are presented with option-based filters on PLPs. A typical example of this would be to filter clothing by size and color as shown here:++++### Option Values++++Option Types define the attributes that can be customized (e.g., size, color, or material) while Option Values specify the available choices for each attribute, like Small, Red, or Cotton.++++Simply enter the values, and click **Add One** if you need to add more values.++After entering all the necessary Option Values, click the **Create** button at the bottom of the page to save the Option.++<Note>When creating or importing products, any new Option Values that haven’t already been added to this Option will be added automatically.</Note>++## Option Management++++Navigating back to the Options page, you’ll see that your newly created option is now listed among your other Options.++Here there are a few ways in which you can manage existing Options:++### Option Ordering++If you’d like to change the order in which Options are displayed on the storefront, e.g., in filters or on product detail pages, you rearrange them by clicking on the 6 dots on the left-hand side and dragging and dropping them into place.++++For example, this will change the PLP filter from this:++++To this:++++The effect is similar on product detail pages:++++### Edit Options++To edit an Option, navigate to the Options tab, and click **Edit** on the option you’d like to edit.++++Feel free to change the Presentation Name, Internal Name, check or uncheck the Filterable box, and add or remove Option Values.++Make sure to click **Update** to save your changes.++### Delete Options++To delete an Option, navigate to the Options tab, and click **Edit** on the option you’d like to delete.++++Click on **Delete**, found in the 3-dot menu at the top of the page, and the Option will be deleted.++## Import Options++Option Values can be automatically imported if you add the appropriate values to the Option columns in a product import file.++To learn more about imports, please refer to the [Product Import](https://spreecommerce.org/docs/user/manage-products/import-products) support article.++## Real-Life Examples: Product Options++These powerful features work together to make products more discoverable, appealing, and purchase-ready for customers.++Let’s dive deep into how these tools can revolutionize your product presentation and drive better business outcomes:++1. [Understanding Product Options: The Power of Choice](https://spreecommerce.org/product-properties-and-product-options-a-strategic-guide-to-improving-conversions-and-seo/#Product-Options)+2. [Bringing It All Together in Spree 5](https://spreecommerce.org/product-properties-and-product-options-a-strategic-guide-to-improving-conversions-and-seo/#Spree-5)+3. [Next Steps](https://spreecommerce.org/product-properties-and-product-options-a-strategic-guide-to-improving-conversions-and-seo/#Next-Steps)diff --git a/docs/user/manage-products/product-properties.mdx b/docs/v5/user/manage-products/product-properties.mdxsimilarity index 93%rename from docs/user/manage-products/product-properties.mdxrename to docs/v5/user/manage-products/product-properties.mdxindex 67cd3ab897..1662aebc1d 100644--- a/docs/user/manage-products/product-properties.mdx+++ b/docs/v5/user/manage-products/product-properties.mdx@@ -1,12 +1,13 @@---title: "Product Properties"description: "How to manage product properties in the Spree open-source eCommerce dashboard"+canonical: "https://spreecommerce.org/docs/v5/user/manage-products/product-properties"---<Warning>-**Starting with Spree 5.2**, Metafields are the **recommended default** for storing custom product attributes, replacing the legacy [Product Properties](/developer/core-concepts/products#product-properties) system. For new projects, use [Metafields](/user/settings/metafields) instead of Properties.+**Starting with Spree 5.2**, Metafields are the **recommended default** for storing custom product attributes, replacing the legacy [Product Properties](/v5/developer/core-concepts/products#product-properties) system. For new projects, use [Metafields](/v5/user/settings/metafields) instead of Properties.-Product Properties are still supported for backward compatibility (until Spree 6.0) but require enabling via `config.product_properties_enabled = true`. See the [upgrade guide](/developer/upgrades/5.1-to-5.2#3-migrate-to-metafields-or-keep-using-properties) for migration details.+Product Properties are still supported for backward compatibility (until Spree 6.0) but require enabling via `config.product_properties_enabled = true`. See the [upgrade guide](/v5/developer/upgrades/5.1-to-5.2#3-migrate-to-metafields-or-keep-using-properties) for migration details.</Warning>Product properties provide detailed specifications, such as dimensions, materials, care instructions, allergen warnings, etc., that help customers make informed purchase decisions.diff --git a/docs/v5/user/manage-products/product-taxonomies.mdx b/docs/v5/user/manage-products/product-taxonomies.mdxnew file mode 100644index 0000000000..1129e821f1--- /dev/null+++ b/docs/v5/user/manage-products/product-taxonomies.mdx@@ -0,0 +1,200 @@+---+title: "Taxonomies"+description: "Learn how to create and manage product taxonomies in the Spree Commerce dashboard."+canonical: "https://spreecommerce.org/docs/user/manage-products/product-taxonomies"+---++Taxonomies let you organize products into groups like categories, brands, or collections.++Taxons are individual nodes or items within a taxonomy, representing specific groups like a category, subcategory, or brand.++A well-designed taxonomy enhances search functionality, improves user experience, and boosts sales by guiding customers through a logical and intuitive shopping journey.++To set up taxonomies for your store, navigate to the Taxonomies tab of the admin dashboard, found under Products.++++Here you will see three automatically created taxonomies that are commonly used in ecommerce:++- Categories - Groups of products based on type or purpose for easy navigation+- Brands - Organizes products by their manufacturer or label+- Collections - Curated groups of products based on themes or trends++## Add a New Taxonomy++To add a new Taxonomy, such as a Category, Collection, or Brand, click **New Taxon** in the top right corner.++This will redirect you to the Taxonomy creation page where you simply need to type in a name.++++Enter the name, and click the **Create** to finalize creation of the taxonomy and you'll be redirected to a page that allows you to manage the new taxonomy.++++## Add Taxons++With the taxonomy created, you can start adding taxons to organize your product catalog more effectively.++To add a taxon, either click **New Taxon** in the top right corner or (in the case of an empty taxonomy), click **Add One** in the middle of the page.++++This opens up the taxon editor page which allows you to define the taxon and add media.++### Presentation++There are four sections that affect how the taxon is presented on the storefront:++- Name - Add a name to be displayed on the frontend and backend+- Description - Add text describing the taxon, optionally displayed on the storefront+- Image - Upload a complimentary image to be displayed on the taxons storefront page+- Square Image - Upload a complimentary square image to optionally be displayed in page sections featuring that taxon++### Taxon Type++Taxon Type allows you to choose between a manual taxon or an automatic taxon.++++#### Manual Taxons++As the name suggests, you must add products manually, either by assigning products to the taxon in bulk, curating them one by one, or by adding the appropriate values to the category column when importing a product file.++#### Automatic Taxons++Allows you to automatically (and dynamically) populate the taxon based on various conditions.++++You can choose whether the products must match all conditions or any of the conditions you define.++The condition types are as follows:++- Product tag - products will only be included if they have a matching tag+- Available on - products will only be included if they were made available within the specified time frame+- Sale - products will only be included if they are marked down (i.e., a Compare At Amount is set)+- Product vendor - products will only be included if they are from a particular vendor++Once you’ve selected the condition type, you can select the value from the dropdown that the condition should be equal to, not equal to, contain, or not contain++++Feel free to add more conditions to further curate the taxon by clicking **Add One**.++### Navigation++Here you can select where the new taxon should be nested.++++The dropdown list will show a list of all taxons available within the taxonomy you're currently managing. Simply select the taxon you’d like to nest the new taxon in.++Start typing the name of the taxon you’d like to nest within to filter the results.++++### Search Engine Listing++Here you can set the meta title, meta description, and the slug for the new taxon.++++### Create Taxon++Once you’ve added the name and defined the taxon type, click **Create** at the bottom of the page to create the taxon, and you’ll receive a notification that the taxon was successfully created.++### Add Products++Once the taxon is created, you can add products to the taxon directly in taxon editor page by clicking **Add Products**, if and only if you chose the manual Taxon Type.++This will open a window that allows you to search for and select the products you’d like to add.++++Start typing to show suggested products, then simply check the boxes of the products you’d like to add and then click **Add selected products**++++You should now see those products listed in the Products section of the taxon editor.++<Note>You can remove individual products by clicking on the **red trash can button** in the far right column.</Note>++++### Sort Order++For merchandising purposes, you may want to change the order in which products in a taxon are presented in the storefront.++To do so, you can select the sort order from the dropdown menu in the Products section of the taxon editor.++++If you choose manual sort order, you can rearrange the ordering by clicking on the 6 dots on the far left and drag and dropping the products into the desired order.++++<Note>Make sure to click **Update** at the bottom of the page if you want to save any changes you’ve made to taxon.</Note>++## Build A Taxonomy Tree++If you’d like to create multiple levels of the taxonomy tree, you can add subtaxons (i.e. nested taxons) to an existing taxon.++Simply click on the 3 dots on the far left of the taxon's row and select **New Nested Taxon**.++++The rest of the process is the same as adding any other taxon.++With some careful consideration, time and little effort, you can create a very deep and detailed taxonomy tree.++++If you’d like to reorganize your taxonomy later, you can do so by drag and dropping taxons into their new positions.++++## Import Taxons++Taxons can be automatically imported if you add the appropriate values to the category columns in a product import file. Just make sure to use the correct naming convention for the taxons to make sure nesting is respected after import, e.g.:++- Categories -\> Fashion -\> Men+- Categories -\> Fashion -\> Women -\> Footwear+- Categories -\> Electronics -\> TVs+- Categories -\> Nutrition -\> Supplements -\> Vitamins++To learn more about imports, please refer to the [Import Products](https://spreecommerce.org/docs/user/manage-products/import-products) article.++## Editing Taxonomies++If you’d like to change the name of a taxonomy, navigate back to the main Taxonomies tab.++++Find the taxonomy you’d like to rename, and click **Edit** on the far-right side.++++Enter the new taxonomy name and click **Update** to save changes.++## Editing Taxons++To edit a taxon, find the taxon you’d like to edit in its respective taxonomy, and click the **Edit** button on the taxon's row.++Feel free to edit the name and description, swap out images, change the nesting, and update search engine listing settings. Make sure to click **Update** to save your changes.++<Note>You cannot edit the Taxon Type of a taxon once created. If you want to change a taxon from manual to automatic (or vice versa), delete the old taxon and create another one with the same name.</Note>++## Translations++If you’re store is multi-language, you can add translations for both taxonomies and taxons.++To learn more about translations, please refer to another support article.++## Real-Life Examples of Categories, Collections, and Brands++1. [Industry-Specific Taxonomy Needs](https://spreecommerce.org/improving-product-discovery-and-conversions-with-product-taxonomies-categories-collections-and-brands/#Industry-Specific)+2. [Multiple Category Trees](https://spreecommerce.org/improving-product-discovery-and-conversions-with-product-taxonomies-categories-collections-and-brands/#Multiple-Category-Trees)+3. [Collection Merchandising](https://spreecommerce.org/improving-product-discovery-and-conversions-with-product-taxonomies-categories-collections-and-brands/#Collection-Merchandising)+4. [Taxonomy Visibility & Product Discovery](https://spreecommerce.org/improving-product-discovery-and-conversions-with-product-taxonomies-categories-collections-and-brands/#Taxonomy-Visibility-Product-Discovery)+5. [Taxonomy Tools](https://spreecommerce.org/improving-product-discovery-and-conversions-with-product-taxonomies-categories-collections-and-brands/#Taxonomy-Tools)diff --git a/docs/v5/user/manage-products/search-products.mdx b/docs/v5/user/manage-products/search-products.mdxnew file mode 100644index 0000000000..6bc2228cff--- /dev/null+++ b/docs/v5/user/manage-products/search-products.mdx@@ -0,0 +1,68 @@+---+title: "Searching Products"+description: "Learn how to search for products in the Spree Commerce dashboard."+canonical: "https://spreecommerce.org/docs/user/manage-products/search-products"+---++As your catalog grows, manually scrolling through the Products list becomes less practical. Fortunately, Spree’s search and filtering tools make it easy to find exactly what you’re looking for - whether it's a specific product, a group by status, or everything under a certain category.++## How to Search & Filter Products++To begin, go to the **Products** tab in the admin dashboard.++++At the top of the page, you’ll find a search bar and a variety of filtering options to help narrow down results.++### Search++++Use the search bar to quickly find products by name or keyword.++Results update automatically to match your query.++To clear the current search, click the **X** next to the query label below the search bar.++### Status & Stock Filters++++The dropdown labeled **Show: All Products** allows you to filter by:++- **Status**: Active, Draft, or Archived+- **Stock availability**: Any stock, In Stock, or Out of Stock++You can apply one filter from each category at a time (e.g., Active and In Stock). The current filter selection will be reflected in the label.++## Additional Filters++++Click the **Filters** button to open more filtering options. These include:++### Taxons++++Here, you can filter by category, collection, brand, or any other taxonomy you’ve defined (e.g., Categories → Men → Shoes or Collections → Spring).++Feel free to select multiple taxons from the dropdown, or select **Without taxon** to filter by products that haven’t been merchandised yet.++To learn more about organizing products into taxons, see **Taxonomies**.++### Tags++++You can also filter products by one or more tags which can be helpful for merchandising or marketing workflows (e.g., Sale, New Arrival, Vegan).++<Note>+ Tags can be added in the product editor or via bulk actions.+</Note>++### Vendors (Enterprise only)++++If you're using Spree Enterprise, you can also filter products by vendor which is incredibly useful for managing multi-vendor catalogs.\ No newline at end of filediff --git a/docs/v5/user/manage-products/stock-levels.mdx b/docs/v5/user/manage-products/stock-levels.mdxnew file mode 100644index 0000000000..4cedc51094--- /dev/null+++ b/docs/v5/user/manage-products/stock-levels.mdx@@ -0,0 +1,54 @@+---+title: "Stock Levels"+description: "Learn how to manage stock levels in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/manage-products/stock-levels"+---++Maintaining accurate stock levels is critical for delivering a smooth customer experience, avoiding overselling, and ensuring clean operational and financial reporting.++There are two main ways to manage inventory, depending on your workflow:++- Edit stock levels individually via the product editor+- Manage inventory directly from the **Stock Items** tab (covered in this article)++<Note>When a customer places an order, stock quantities are automatically reduced based on the quantity purchased. Similarly, when items are returned and marked as resellable, the stock quantities will automatically increase.</Note>++## How to Manage Stock Levels++To manage stock levels across your catalog, navigate to **Products → Stock → Stock Items.**++++Here you’ll see a list of all product variants, separated by stock location (i.e., if you have two stock locations, each variant will have two rows in the table).++You can use the search bar to filter by product name, SKU (partial or full), or stock location.++++This makes it easier to manage stock updates when, for example, receiving a new shipment to a specific warehouse or restocking a particular product line.++## Updating Stock Levels++++To adjust stock levels:++1. Locate the variant you want to update+2. Enter the new quantity in the **Count On Hand** column+3. Click **Update** at the end of the row++You’ll see a green confirmation popup at the top of the screen once the update is saved.++<Note>Each variant/location combination must be updated independently.</Note>++## Enabling Backorders++++You can allow a product to be sold even when its inventory reaches zero by marking it as **Backorderable**.++To do so, simply **check** or **uncheck the box** in the **Backorderable** column in the associated row.++This setting saves automatically, so there’s **no need to click Update**.++<Warning>Only mark products as backorderable if you plan to restock them. Enabling backorders for discontinued or limited-stock items may result in customer service issues.</Warning>\ No newline at end of filediff --git a/docs/v5/user/manage-products/stock-transfers.mdx b/docs/v5/user/manage-products/stock-transfers.mdxnew file mode 100644index 0000000000..13b0164130--- /dev/null+++ b/docs/v5/user/manage-products/stock-transfers.mdx@@ -0,0 +1,65 @@+---+title: "Stock Transfers"+description: "Learn how to create stock transfers in the Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/manage-products/stock-transfers"+---++Stock transfers allow you to move inventory between stock locations - a critical feature for multi-warehouse operations. This helps keep inventory balanced across your network, improves fulfillment speed, and reduces shipping costs by positioning products closer to customers.++<Note>+ Before you can create stock transfers, you must first set up additional stock locations.+ See: [<u>Settings → Locations</u>](https://spreecommerce.org/docs/user/settings/locations).+</Note>++## How to Create a Stock Transfer++To create a new stock transfer, navigate to **Products → Stock → Stock Transfers**.++++Click **New Stock Transfer** in the top-right corner, and you’ll be redirected to the stock transfer creation form.++++Here you’ll see two distinct sections that allow you to:++## Configure Transfer Details++++At the top of the form, you can specify the details of the stock transfer:++- **Origin Location**: Select the warehouse the stock will be transferred from+- **Destination Location**: Select the warehouse the stock will be transferred to+- **Reference (optional)**: Add a label or note to help identify the transfer (e.g., Q2 Restock - East Coast)++## Add Products to the Transfer++++At the bottom of the form, you can add the products to be transferred.++To do so, click **\+ Add Products** and a search window will open, allowing you to start typing a product name to find matching variants.++++Please select a variant and then click **Add selected variant** to add it to the stock transfer.++++Now simply enter the number of units to be transferred for each variant.++<Note>+ You can only transfer quantities that are currently in stock at the origin location.+</Note>++## Finalize the Transfer++When you're ready:++- Review the details+- Click **Create** to process the transfer++The inventory counts at each location will be updated immediately to reflect the transfer (assuming the physical movement of stock has already occurred) and a record of the transfer will be added to the Stock Transfers tab.++diff --git a/docs/v5/user/manage-products/translations.mdx b/docs/v5/user/manage-products/translations.mdxnew file mode 100644index 0000000000..1f0af4376a--- /dev/null+++ b/docs/v5/user/manage-products/translations.mdx@@ -0,0 +1,69 @@+---+title: "Translations"+description: "Learn how to manage and track product translations across all your store's locales in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/manage-products/translations"+---++The Translations page gives you a single place to see how well your product catalog is translated across every language your store supports. Rather than hunting through individual product pages, you can see at a glance which products have been translated and which still need attention — and use bulk import/export to handle translations in volume.++To access Translations, navigate to **Products → Translations** in the admin dashboard.++++<Note>The languages shown on this page are determined by your Markets configuration. If you don't see any locales listed, you'll need to set up additional markets first. See [<u>Settings → Markets</u>](https://spreecommerce.org/docs/user/settings/markets) for more details.</Note>++## Translation Coverage++At the top of the page, you'll see a coverage summary table with one row per locale your store supports (excluding your default language). Each row shows:++- **Locale** - The language code (e.g., `fr`, `de`, `es`)+- **Translated** - How many products have a translation for that locale+- **Total** - The total number of products in your catalog+- **Coverage** - The percentage translated, shown as both a number and a visual progress bar++This gives you a quick health check on your localization progress without needing to export any data.++++## Product Translation Status++Below the coverage table, you'll see a paginated list of all your products. Each product has a column for every configured locale, showing either a checkmark (✓) if a translation exists or a dash (—) if it's missing.++++To edit a product's translations, click on the product name. This will open the translation drawer where you can add or update translated content for that product.++++## Bulk Export Translations++If you prefer to manage translations in a spreadsheet, you can export your entire translation dataset as a CSV file.++Click **Export** in the top-right corner of the page.++++Click **Export** to confirm, and a download link will be sent to the email address associated with your admin account.++## Bulk Import Translations++Once you've updated your translations in the exported file (or built a new file from scratch), you can import them back in bulk.++Click **Import** in the top-right corner of the page. This opens the import side panel.++++1. Drag and drop your CSV file into the upload area, or click **browse files** to select it from your computer.+2. Select the correct delimiter used in your file (comma, pipe, semicolon, or tab).+3. Click **Create** to proceed to the field mapping step.+4. Review the field mapping and adjust any columns that weren't matched automatically, then click **Continue** to submit.++Once submitted, you'll be redirected to a processing screen where you can monitor the import progress. Any rows with errors will be flagged with a message so you can fix and re-import them.++<Note>The translation import uses the same importer infrastructure as the product importer. If you're familiar with importing products, the process will feel very similar.</Note>++## Next Steps++- [<u>Settings → Markets</u>](https://spreecommerce.org/docs/user/settings/markets) — Configure which languages and locales your store supports+- [<u>Import Products</u>](https://spreecommerce.org/docs/user/manage-products/import-products) — Learn how to bulk import product data+- [<u>Export Products</u>](https://spreecommerce.org/docs/user/manage-products/export-products) — Learn how to export your product catalogdiff --git a/docs/v5/user/migration/migrate-from-shopify.mdx b/docs/v5/user/migration/migrate-from-shopify.mdxnew file mode 100644index 0000000000..f537ab65fd--- /dev/null+++ b/docs/v5/user/migration/migrate-from-shopify.mdx@@ -0,0 +1,267 @@+---+title: Migrate from Shopify+description: Step-by-step guide to migrating your products and customers from Shopify to Spree Commerce using CSV imports+canonical: "https://spreecommerce.org/docs/user/migration/migrate-from-shopify"+---++## Overview++Spree Commerce provides a built-in CSV import system that makes migrating from Shopify straightforward. Since Shopify exports data in CSV format and Spree supports flexible column mapping, you can import your products and customers with minimal manual transformation.++This guide covers:+- Exporting data from Shopify+- Preparing CSV files for Spree+- Importing products (with variants, images, and categories)+- Importing customers (with addresses)+- Post-migration checklist++## Exporting Data from Shopify++### Products++1. In your Shopify admin, go to **Products**+2. Click **Export** and choose **All products** (or a filtered selection)+3. Select **Plain CSV file** format+4. Download the file++### Customers++1. In your Shopify admin, go to **Customers**+2. Click **Export** and choose **All customers**+3. Select **Plain CSV file** format+4. Download the file++## Products Migration++### Column Mapping++Spree's import system lets you map CSV columns to Spree fields during the import process. Here's how Shopify columns map to Spree fields:++| Shopify Column | Spree Field | Notes |+|---------------|-------------|-------|+| `Handle` | `slug` | **Required.** URL-friendly product identifier |+| `Variant SKU` | `sku` | **Required.** Stock keeping unit |+| `Title` | `name` | **Required.** Product name |+| `Variant Price` | `price` | **Required.** No currency symbols |+| `Status` | `status` | `active`, `draft`, or `archived` |+| `Body (HTML)` | `description` | HTML description is supported |+| `SEO Title` | `meta_title` | Meta title for SEO |+| `SEO Description` | `meta_description` | Meta description for SEO |+| `Tags` | `tags` | Comma-separated tags |+| `Variant Compare At Price` | `compare_at_price` | Original price for sale display |+| `Variant Grams` | `weight` | See weight conversion note below |+| `Variant Weight Unit` | `weight_unit` | `g`, `kg`, `lb`, or `oz` |+| `Image Src` | `image1_src` | Product image URL |+| `Option1 Name` | `option1_name` | e.g., `Size`, `Color` |+| `Option1 Value` | `option1_value` | e.g., `Small`, `Red` |+| `Option2 Name` | `option2_name` | Second option name |+| `Option2 Value` | `option2_value` | Second option value |+| `Option3 Name` | `option3_name` | Third option name |+| `Option3 Value` | `option3_value` | Third option value |+| `Cost per item` | — | Not directly imported, can be set via metafields |+| `Vendor` | — | Can be imported as a metafield or tag |+| `Product Category` | `category1` | Requires format adjustment (see below) |++### Step-by-Step Import++<Steps>+ <Step title="Upload the CSV">+ In Spree Admin, go to **Products → Import** and upload your Shopify products CSV file.+ </Step>+ <Step title="Map the columns">+ Spree will auto-detect columns where names are similar. For Shopify-specific columns, you'll need to manually map them:++ - Map `Handle` → `slug`+ - Map `Title` → `name`+ - Map `Variant SKU` → `sku`+ - Map `Variant Price` → `price`+ - Map `Body (HTML)` → `description`+ - Map `Variant Compare At Price` → `compare_at_price`+ - Map `Image Src` → `image1_src`+ - Map `Variant Grams` → `weight`+ - Map `Variant Weight Unit` → `weight_unit`+ - Map `SEO Title` → `meta_title`+ - Map `SEO Description` → `meta_description`+ - Map option and tag columns as needed+ </Step>+ <Step title="Review and start the import">+ Once all required fields are mapped, click **Start Import**. The import runs in the background and you can track progress in the admin.+ </Step>+</Steps>++### Multi-Variant Products++Both Shopify and Spree handle multi-variant products the same way in CSV format — multiple rows share the same `Handle`/`slug`:++```csv+Handle,Title,Variant SKU,Variant Price,Option1 Name,Option1 Value,Option2 Name,Option2 Value+my-tshirt,My T-Shirt,TSHIRT-001,29.99,,,+my-tshirt,My T-Shirt,TSHIRT-S-RED,29.99,Size,Small,Color,Red+my-tshirt,My T-Shirt,TSHIRT-M-RED,29.99,Size,Medium,Color,Red+my-tshirt,My T-Shirt,TSHIRT-L-RED,29.99,Size,Large,Color,Red+```++- The first row (no option values) creates the product and master variant+- Subsequent rows with the same `Handle` create additional variants++This format works directly with Spree's importer — no transformation needed.++### Handling Images++Shopify exports image URLs in the `Image Src` column. Map this to `image1_src` in Spree. The importer will download and attach images asynchronously from the provided URLs.++<Note>+ Shopify CDN URLs remain accessible after export, so images will download successfully. If you have multiple images per product, Spree supports `image1_src`, `image2_src`, and `image3_src` fields. For products with more than 3 images, you can add additional images manually after import.+</Note>++### Handling Categories++Shopify uses `Product Category` (their taxonomy) and `Type` (free-form). Spree uses a hierarchical taxonomy format with `->` separators.++To map Shopify categories to Spree, you may need to adjust the values in your CSV before import:++```+# Shopify format+Product Category: Apparel & Accessories > Clothing > Shirts & Tops++# Spree format (use -> separator)+category1: Categories -> Clothing -> Shirts & Tops+```++You can either:+1. Pre-process your CSV to convert the category format+2. Create your taxonomy in Spree first, then use the `category1`, `category2`, and `category3` fields during mapping++### Weight Conversion++Shopify's `Variant Grams` column is **always in grams** regardless of the `Variant Weight Unit` setting. When mapping to Spree:++- Map `Variant Grams` → `weight`+- Map `Variant Weight Unit` → `weight_unit`+- If `Variant Weight Unit` is missing, the weight will be treated as grams++### Columns You Can Skip++These Shopify-specific columns don't have direct Spree equivalents and can be safely skipped:++- `Vendor` — consider importing as a tag or metafield+- `Published` — use `status` instead (`active` = published)+- `Variant Inventory Tracker` — Spree handles inventory tracking differently+- `Variant Fulfillment Service` — not applicable+- `Variant Requires Shipping` — controlled by shipping categories in Spree+- `Variant Taxable` — controlled by tax categories in Spree+- `Variant Barcode` — can be added as a metafield+- `Gift Card` — Spree has its own gift card system+- `Google Shopping / *` — not imported (legacy Shopify columns)++## Customers Migration++### Column Mapping++Shopify's customer CSV maps closely to Spree's customer import schema:++| Shopify Column | Spree Field | Notes |+|---------------|-------------|-------|+| `Email` | `email` | **Required.** Customer email |+| `First Name` | `first_name` | Customer first name |+| `Last Name` | `last_name` | Customer last name |+| `Phone` | `phone` | Primary phone number |+| `Accepts Email Marketing` | `accepts_email_marketing` | `yes`/`no` format works directly |+| `Tags` | `tags` | Comma-separated tags |+| `Default Address Company` | `company` | Company name |+| `Default Address Address1` | `address1` | Street address line 1 |+| `Default Address Address2` | `address2` | Street address line 2 |+| `Default Address City` | `city` | City |+| `Default Address Province Code` | `province_code` | ISO state/province code (e.g., `NY`, `CA`) |+| `Default Address Country Code` | `country_code` | ISO country code (e.g., `US`, `GB`) |+| `Default Address Zip` | `zip` | Postal/zip code |+| `Note` | — | Not directly imported, can be added as a metafield |+| `Tax Exempt` | — | Not directly imported |+| `Total Spent` | — | Read-only in Shopify, not imported |+| `Total Orders` | — | Read-only in Shopify, not imported |++### Step-by-Step Import++<Steps>+ <Step title="Upload the CSV">+ In Spree Admin, go to **Customers → Import** and upload your Shopify customers CSV file.+ </Step>+ <Step title="Map the columns">+ Map the Shopify columns to Spree fields. Most columns will auto-map since the field names are similar. You'll need to manually map the address fields:++ - Map `Default Address Company` → `company`+ - Map `Default Address Address1` → `address1`+ - Map `Default Address Address2` → `address2`+ - Map `Default Address City` → `city`+ - Map `Default Address Province Code` → `province_code`+ - Map `Default Address Country Code` → `country_code`+ - Map `Default Address Zip` → `zip`+ </Step>+ <Step title="Review and start the import">+ Once all required fields are mapped, click **Start Import**. New customer accounts will be created with randomly generated passwords.+ </Step>+</Steps>++<Note>+ Imported customers will need to use the **Forgot Password** flow to set their password, as Shopify does not export passwords. Consider sending a welcome email to imported customers with a password reset link.+</Note>++### Customer Address Handling++Shopify only exports the **default address** in the customer CSV. The Spree importer creates this as both the billing and shipping address for each customer. If your customers have multiple addresses in Shopify, only the default will be migrated.++## Post-Migration Checklist++After importing your data, review the following:++<AccordionGroup>+ <Accordion title="Products">+ - [ ] Verify product counts match between Shopify and Spree+ - [ ] Check that variants and options imported correctly+ - [ ] Confirm images downloaded successfully+ - [ ] Review category/taxonomy assignments+ - [ ] Set up tax categories and shipping categories if not mapped during import+ - [ ] Configure inventory tracking and stock levels+ - [ ] Review product statuses (active/draft/archived)+ </Accordion>++ <Accordion title="Customers">+ - [ ] Verify customer counts match+ - [ ] Check that addresses imported correctly+ - [ ] Send password reset emails to imported customers+ - [ ] Verify email marketing opt-in status+ </Accordion>++ <Accordion title="Not Covered by CSV Import">+ These Shopify resources require additional migration steps:+ - **Orders** — Historical orders are not imported via CSV. Use the [Spree API](/developer/storefront/rest-api) for programmatic order migration if needed+ - **Discount codes / Promotions** — Recreate manually in Spree Admin or via API+ - **Collections** — Set up as Taxons in Spree+ - **Pages / Blog posts** — Migrate content manually or via API+ - **Gift cards** — Recreate in Spree's gift card system+ - **Customer passwords** — Shopify does not export passwords; customers must reset them+ </Accordion>+</AccordionGroup>++## Troubleshooting++### Common Issues++**Import shows failed rows**++Check the import details page in the admin to see row-level errors. Common causes:+- Missing required fields (`slug`, `sku`, `name`, `price` for products; `email` for customers)+- Invalid price format (remove currency symbols)+- Duplicate SKUs across products++**Images not appearing**++Images are downloaded asynchronously after import. Allow some time for the background jobs to complete. If images still don't appear, verify the URLs are accessible.++**Categories not created**++Ensure category values use the `Taxonomy -> Taxon -> Child` format with ` -> ` as the separator (spaces around the arrow).++**Special characters in CSV**++Ensure your CSV is UTF-8 encoded. If exported from Shopify as "CSV for Excel", it may include a BOM (Byte Order Mark) which Spree handles correctly.diff --git a/docs/v5/user/orders/cancelling-orders.mdx b/docs/v5/user/orders/cancelling-orders.mdxnew file mode 100644index 0000000000..52295a9204--- /dev/null+++ b/docs/v5/user/orders/cancelling-orders.mdx@@ -0,0 +1,51 @@+---+title: "Cancelling Orders"+description: "Learn how to cancel orders in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/orders/cancelling-orders"+---++There may be times when you need to cancel an order, whether to accommodate a customer request, flag a fraudulent transaction, or resolve issues with inventory or payments.++Spree allows you to cancel orders directly from the admin dashboard in just a few steps.++## How to Cancel an Order++Navigate to the **Orders** tab of the admin dashboard.++++Find and click on the order you want to cancel to open its detail page.++++In the top-right corner, click the **three-dot menu**, then select **Cancel Order** from the dropdown.++++Once confirmed, the order will be cancelled and its status will be updated automatically.++<Warning>+ Cancelling an order is irreversible.+</Warning>++## What Happens After Cancellation++### Order Status++- The order’s shipment state will be updated to Cancelled.+- The payment state may also change to Void or Refunded, depending on whether payment has already been captured.++### Payment Refunds++Refunds are not always automatic. Whether the payment is refunded depends on:++- Your payment service provider (PSP)+- The payment method used+- Whether the payment had already been captured++If the payment state does not change to Refunded, you'll need to issue a refund manually.++Learn more about refunds and returns here:++- [<u>Refunding Orders</u>](https://spreecommerce.org/docs/user/orders/refunding-orders)+- [<u>Returns Processing</u>](https://spreecommerce.org/docs/user/returns/returns-processing)diff --git a/docs/v5/user/orders/creating-orders.mdx b/docs/v5/user/orders/creating-orders.mdxnew file mode 100644index 0000000000..c3e16c6b0c--- /dev/null+++ b/docs/v5/user/orders/creating-orders.mdx@@ -0,0 +1,121 @@+---+title: "Creating Orders"+description: "Learn how to manually create orders as an admin in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/orders/creating-orders"+---++Depending on your business model, creating orders manually may be a common workflow - whether it’s to handle customer service scenarios, B2B orders, or backend sales operations. Follow this step by step guided flow that lets you build the order step by step.++## 1. Start a New Order++Navigate to the **Orders** tab in the admin dashboard and click **New Order** in the top-right corner.++++You’ll be redirected to a short order setup form where you must:++- **Select Currency** - choose the appropriate currency for the order+- **Choose a Customer**+ - Select an existing customer+ - _OR_ enter a new customer’s email to create a customer record on the fly++++Once these details are filled in, click **Create** to continue.++## 2. Add Line Items++++You’ll now land on the order editor, with the order in draft status.++Begin by clicking **Add Line Item** at the top of the page to add items to the order.++++Search and select the desired product variant and click **Add Selected Variant** to add it to the order++<Note>You can only add one product variant at a time. Repeat the step for multiple items.</Note>++## 3. Shipping & Billing Address Logic++After you add the first line item, Spree handles customer addresses based on whether it’s a new or existing customer:++### Existing Customer++++The customers default shipping and billing addresses are automatically used, but you can edit them via the **three-dot menu** in the Customer section.++### New Customer++++You must manually add a shipping and billing address:++1. Locate the **Customer** section+2. Click **\+ New Shipping Address** and fill in the form+3. Click **\+ New Billing Address** (or select "Same as Shipping")++## 4. Add a Shipping Method++++Once a line item is added, a shipment will appear in the Shipment section, with a default shipping method selected.++To change it:++1. Click the **pencil (edit)** icon next to the shipping method+2. Select the desired method from the dropdown+3. Click **Save**++## 5. Apply Promotions++++Admins can manually apply valid **Promotion Codes** to the order. To do so:++1. Scroll to the **Promotions** section+2. Click **\+ Add Promotion Code**+3. Enter the coupon code and apply it++If valid, any applicable discounts will be reflected in the order total.++## 6. Add Order Adjustments++++To manually adjust the order total (e.g., for discounts, fees, or custom credits):++1. Scroll to the **Adjustments** section+2. Click **\+ New Adjustment**+3. Enter a **Label** and set an **Amount**:+ 1. Positive amount = charge+ 2. Negative amount = credit+4. Click **Create**++Adjustments will be reflected in the cost summary.++## 7. Add a Payment++++There are three options for applying payment to the order:++### Create a Manual Payment++++Click **\+ New Payment Method** and fill in:++- **Amount** - defaults to order total+- **Payment Method** - e.g., Stripe, bank transfer, etc.+- **Payment Source** - saved card (if available)++Click **Create** to add the payment.++<Note>If the customer has no saved card, you won’t be able to use some methods.</Note>++## 8. Fulfill the Order++Once all items, payments, promos, and adjustments are in place, you can proceed to ship the order once you have received payment from the customer. For details on fulfillment, see [<u>Processing Orders</u>](https://spreecommerce.org/docs/user/orders/processing-orders).diff --git a/docs/v5/user/orders/editing-orders.mdx b/docs/v5/user/orders/editing-orders.mdxnew file mode 100644index 0000000000..32d6a67fd0--- /dev/null+++ b/docs/v5/user/orders/editing-orders.mdx@@ -0,0 +1,140 @@+---+title: "Editing Orders"+description: "Learn how to edit existing orders in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/orders/editing-orders"+---++Editing orders in the admin dashboard allows you to provide flexible customer support - whether that means adding items, correcting addresses, upgrading shipping, or adjusting payments. This is especially common in B2B scenarios, where bulk pricing, negotiated terms, or inventory changes may require updates after an order is placed.++## How to Edit an Order++To edit an order, navigate to **Orders** in the admin dashboard.++++Click the order you’d like to modify to open the order details page.++++You can edit most aspects of an order (except the order number). Below are the key areas you can modify.++## Add Line Items++++You may need to add products at a customer’s request—for example, to include additional items, upgrades, or promotional gifts.++To add a product:++1. Click **\+ Add line item** at the top of the line items section.+2. Select the desired variant from the form, set the quantity and click **Add selected variant**++## Adjust Quantity of Line Items++++To adjust quantity of existing line items:++1. Click **Show details** to expand line items+2. Click the **three-dot menu** on the line item you’d like to adjust+3. Enter the updated quantity and click **Save**++<Warning>If adding items or adjusting quantities increases the order total, you’ll need to add an additional payment (unless the item is added at no charge).</Warning>++## Remove Line Items++++You may remove items due to customer requests, partial cancellations, or stock issues.++To remove a product:++1. Click **Show details** to expand line items+2. Click the **three-dot menu** on the line item you’d like to remove+3. Select **Delete** from the menu++<Warning>If the order has already been paid, issue a partial refund. If the payment is still due, delete the existing payment and create a new one with the correct amount.</Warning>++## Change Shipping or Billing Address++++To update addresses:++1. In the **Customer** section, click the **three-dot menu**+2. Edit the shipping or billing address as needed++<Warning>If the new shipping address changes the shipping zone, you may need to update the shipping method to reflect available options for that region.</Warning>++## Change Fulfillment Location++++If you manage multiple stock locations, you can change where an item is fulfilled from.++To change fulfillment location:++1. In the **Shipment** section, click the **split arrow icon** next to the line item+2. Select a different stock location and click **Move**++This will split the order into multiple shipments, each with its own shipping cost.++<Warning>If shipping costs change, you’ll need to update the payment accordingly.</Warning>++## Change Shipping Method++++To update the shipping method:++1. Click the pencil icon next to the current shipping method+2. Select a new method from the dropdown+3. Click **Save**++<Warning>If the new method has a different cost, adjust the payment to reflect the updated total.</Warning>++## Add Adjustments++++To manually adjust the order total (e.g., for discounts, fees, or custom credits):++1. Scroll to the **Adjustments** section+2. Click **\+ New Adjustment**+3. Enter a Label and set an Amount:+ - Positive amount = charge+ - Negative amount = credit+4. Click **Create**++Adjustments will be reflected in the cost summary.++## Add Payments++++When order changes increase the total, you’ll need to add payment to keep the order balanced.++There are three options:++### Create a New Payment++Click **\+ New Payment** and configure:++- **Amount** (defaults to remaining balance)+- **Payment Method**+- **Payment Source** (saved cards or accounts, if applicable)++Click **Create** to add the payment.++<Note>Depending on the payment method and its configuration, the payment may be captured automatically or require manual capture. If the customer has no saved payment source for the selected method, you won’t be able to charge it directly.</Note>++## Remove Payments++To delete a payment:++1. Click the **three-dot menu** next to the payment+2. Select **Delete**++If the payment status is **Paid**, it cannot be deleted - you must issue a refund instead.++See [<u>Refunding Orders</u>](https://spreecommerce.org/docs/user/orders/refunding-orders) for detailed instructions.diff --git a/docs/v5/user/orders/exporting-orders.mdx b/docs/v5/user/orders/exporting-orders.mdxnew file mode 100644index 0000000000..96dc6db93e--- /dev/null+++ b/docs/v5/user/orders/exporting-orders.mdx@@ -0,0 +1,28 @@+---+title: "Export Orders"+description: "Learn how to export orders to CSV in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/orders/exporting-orders"+---++As an admin, you might want to export order data for a variety of reasons - tracking sales trends, reconciling financial records, or sharing order details with other teams. Spree makes it easy to export this data in a clean CSV format.++## How to Export Orders++To export orders to CSV, navigate to the **Orders** tab of the admin dashboard.++++Click the **Export** button in the top-right corner, and a popup will appear++<Note>+ If you only want to export a subset of the data, apply filters using the filter controls at the top of the order view before clicking Export.+</Note>++++Next, choose which records to export:++- **Filtered Records** - Exports only the orders currently visible based on your applied filters (e.g., date range, payment state).+- **All** - Exports the entire order history.++Once selected, click **Export**, annd a download link for the CSV file will be sent to the email address associated with your admin user account.diff --git a/docs/v5/user/orders/order-adjustments.mdx b/docs/v5/user/orders/order-adjustments.mdxnew file mode 100644index 0000000000..ba6c28205f--- /dev/null+++ b/docs/v5/user/orders/order-adjustments.mdx@@ -0,0 +1,72 @@+---+title: "Order Adjustments"+description: "Learn how to create and settle order adjustments in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/orders/order-adjustments"+---++# Order Adjustments++Order adjustments let you manually add a charge or credit to an existing order - ideal for handling things like special fees, discounts, or post-purchase updates.++## How to Create an Adjustment++To create an order adjustment, navigate to the **Orders** tab in the admin dashboard.++++Find the order you'd like to adjust and click on it to open the order page.++++Scroll to the **Adjustments** section and click **New Adjustment** to open the adjustment creation form.++++Fill out the form:++- **Label** - A name for the adjustment (e.g., "Custom Discount", "Packaging Fee")+- **Amount** - Use a **positive value** for a charge or a **negative value** for a credit.++Finally, click **Create** to add the new adjustment.++## Handling the Payment or Refund++Once the adjustment has been created, it will need to be settled manually. Depending on whether it’s a charge or credit, follow one of the steps below:++### Credit (Negative Amount)++To manually refund the adjustment amount, click the **three-dot menu** next to the payment and select **Refund**.++++This will open a refund form where you can enter the amount to be refunded.++++After entering the amount and selecting a refund reason, click **Create** to process the refund.++<Note>Refund behavior depends on the payment method used - some refunds can be processed automatically, while others may require manual handling.</Note>++### Charge (Positive Amount)++There are two methods to charge a customer in the event of a positive adjustment.++### Automatated Payment++To charge a customer, click **New Payment** in the Payments section.++++This will open the payment form where you can select the amount to charge the customer and the payment method to be charged.++++Click **Create** after entering the details. The customer’s payment method will then be automatically charged for the outstanding balance.++## Close the Adjustment++Once the adjustment has been handled, click the **three-dot menu** next to the adjustment, and select **Close** to mark the adjustment as finalized.++++<Note>Closing an adjustment helps track which ones have been settled, especially when managing refunds or manual charges.</Note>diff --git a/docs/v5/user/orders/order-states.mdx b/docs/v5/user/orders/order-states.mdxnew file mode 100644index 0000000000..f3612e7bb5--- /dev/null+++ b/docs/v5/user/orders/order-states.mdx@@ -0,0 +1,72 @@+---+title: "Order States"+description: "Learn how to use order states to track and manage orders in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/orders/order-states"+---++Effective order management is essential for any ecommerce business - it ensures timely processing, accurate fulfillment, and a smooth customer experience. In Spree, Order States help you track and manage each stage of an order, so you can quickly identify next steps or potential issues.++To review order states, navigate to the **Orders** tab of the admin dashboard.++++You’ll see a list of all orders placed in your store, with two key columns:++- **Payment State** - shows the current payment status+- **Shipment State** - shows the current shipping status++Together, these determine the overall state of the order.++## Payment States++The **Payment State** indicates the current status of payments associated with the order. An order can have multiple payments, but Spree will show the relevant state based on the most recent or net balance.++| **Payment State** | **Description** |+| ---------------------- | ------------------------------------------------------------------------- |+| Paid | The order total has been fully paid |+| Balance Due | The total payments are less than the order total |+| Credit Owed | The total payments exceed the order total (e.g. after removing items) |+| Refunded | The order has been fully refunded |+| Partially Refunded | One or more refunds have been issued, but the order is not fully refunded |+| Failed | The most recent payment attempt failed |++<Note>You cannot manually set the payment state. It updates automatically based on actions like capturing payments, issuing refunds, or adjusting the order total.</Note>++## Shipment States++The **Shipment State** reflects the current status of all shipments tied to an order. Orders can have one or multiple shipments depending on stock locations or backorders.++| **Shipment State** | **Description** |+| ------------------ | ---------------------------------------------------------------------------------------------------------- |+| Shipped | All associated shipments have been marked as shipped |+| Partial | At least one shipment is shipped, but others are not / or some items are marked sold but not in a shipment |+| Ready | All shipments are packed and ready to be shipped |+| Backorder | At least one shipment contains inventory that is currently backordered |+| Pending | Shipments are created but not ready to be fulfilled (e.g., awaiting payment) |+| Cancelled | The order has been cancelled |++<Note>Like payment state, shipment state is managed automatically based on order and fulfillment actions.</Note>++## Using Order States Effectively++Understanding these states makes it easier to manage operations and know exactly what action to take.++Here are some common scenarios:++| **Payment State** | **Shipment State** | **Suggested Action** |+| ---------------- | ----------------- | -------------------------------------------------- |+| Paid | Shipped | No action needed – order is complete |+| Paid | Ready | Ship the order |+| Balance Due | Pending | Capture payment or request payment from customer |+| Credit Owed | Partial | Refund the owed amount |+| Failed | Pending | Review payment method or contact the customer |+++## Next Steps++Now that you're familiar with how order states work, we recommend checking out related docs for deeper insights:++- [<u>Processing Orders</u>](https://spreecommerce.org/docs/user/orders/processing-orders) - Learn how to capture payments and ship orders+- [<u>Cancelling Orders</u>](https://spreecommerce.org/docs/user/orders/cancelling-orders) - Learn how to cancel orders+- [<u>Creating Orders</u>](https://spreecommerce.org/docs/user/orders/creating-orders) - Learn how to create orders manually as an admin+- [<u>Returns Processing</u>](https://spreecommerce.org/docs/user/returns/returns-processing) - Learn how to process returnsdiff --git a/docs/v5/user/orders/processing-orders.mdx b/docs/v5/user/orders/processing-orders.mdxnew file mode 100644index 0000000000..e54279c0db--- /dev/null+++ b/docs/v5/user/orders/processing-orders.mdx@@ -0,0 +1,96 @@+---+title: "Processing Orders"+description: "Learn how to process orders in the Spree Commerce admin dashboard,"+canonical: "https://spreecommerce.org/docs/user/orders/processing-orders"+---++Efficient order processing is essential for running a successful ecommerce business. In Spree, processing an order typically involves two key steps: capturing payment and fulfilling the order.++To process an order, navigate to the Orders tab of the Spree dashboard.++++From here, simply click on the order you want to process to open the order page.++++Here you’ll see a full overview of the order, including payment and shipment details.++## Payment Capture++++Some businesses (especially B2C) choose to auto-capture payments when an order is placed. Others prefer to manually capture payments later - for example, after stock is verified or fraud checks are completed.++<Note>If you are auto-capturing payments, proceed to Order Fulfillment.</Note>++If the order has a Balance Due payment status, follow one of the options below:++### Option 1: Manually Capture an Existing Payment++++If the payment is already authorized (e.g., via credit card or bank transfer), you can capture it manually:++1. Click the **three-dot menu** next to the existing payment.+2. Select **Capture**.++The payment status will update to Paid, and you will now be able to fulfill the order via the shipment section.++### Option 2: Add a New Payment++++If the original payment failed, or if the customer wants to pay via a different method, you can create a new payment.++Simply click the **New Payment** to open the payment creation form, and fill out the fields++- Amount (defaults to order total)+- Payment Method+- Payment Source (e.g. saved credit card)++Click **Create** to finalize the new payment.++You can now either:++- Capture the payment immediately if the details are saved++<Note>Depending on the payment method used for the order, the refund or capture process may happen automatically or may require manual action.</Note>++## Order Fulfillment++++Once payment has been captured, you're ready to fulfill the order via the **Shipments** section.++Before shipping, make sure you have:++- The correct tracking number+- The correct carrier, based on the customer’s shipping selection++### Add Tracking Details++++To add tracking details to the shipment:++1. Click the **\+** icon in the Tracking subsection.+2. Enter the tracking number.+3. Click **Save**.++### Ship the Order++Double-check that everything is correct and click **Ship** to complete the order.++The order’s shipment status will update to **Shipped**, and the customer will receive a confirmation email with tracking details.++## Order Completed++++At this point, the order will have:++- **Payment State**: Paid+- **Shipment State**: Shipped++This means the order has been successfully processed and is now complete from your business’ point of view. All that’s left is for the customer to receive their shipment.diff --git a/docs/v5/user/orders/refunding-orders.mdx b/docs/v5/user/orders/refunding-orders.mdxnew file mode 100644index 0000000000..ac1ade04ae--- /dev/null+++ b/docs/v5/user/orders/refunding-orders.mdx@@ -0,0 +1,41 @@+---+title: "Refunding Orders"+description: "Learn how to refund orders in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/orders/refunding-orders"+---++Refunding orders is a key part of running a smooth ecommerce operation. Whether you're handling customer complaints, returns, or correcting billing errors, issuing refunds helps maintain trust, ensure financial accuracy, and stay compliant with store policies.++## How to Refund an Order++To refund an order, navigate to the **Orders** tab in the admin dashboard.++++Click on the order you'd like to refund to open its detail page.++++Scroll to the **Payments** section, and click the **three-dot menu** to the right of the payment you want to refund and select **Refund**.++++This will open a simple refund form.++## Completing the Refund++++On the refund page, you’ll be able to:++- **Set the refund amount** (full or partial)+- **Choose a refund reason** from the dropdown++Once complete, click **Create** to process the refund.++The order’s payment state will be updated to reflect the refund:++- **Refunded** for full refunds+- **Partially Refunded** if only a portion was refunded++<Warning>Refund behavior depends on the payment method. Some providers (like Stripe) automatically process refunds. Others (like offline/manual payments) may require you to issue the refund manually outside of Spree. Always double-check which payment method was used and whether the refund was successfully processed through your payment provider</Warning>diff --git a/docs/v5/user/orders/searching-orders.mdx b/docs/v5/user/orders/searching-orders.mdxnew file mode 100644index 0000000000..75fad0c028--- /dev/null+++ b/docs/v5/user/orders/searching-orders.mdx@@ -0,0 +1,121 @@+---+title: "Searching Orders"+description: "Learn how to search and filter orders in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/orders/searching-orders"+---++As your store grows, quickly locating specific orders becomes essential for customer support, reporting, and daily operations.++Spree’s updated table view makes it easy to search, sort, filter, and customize how orders are displayed.++To search for orders, navigate to the **Orders** tab in the admin dashboard.++++From here, there are a number of ways in which you can find the orders you are looking for.++## **Search Bar**++++At the top of the page, you’ll find the search bar.++You can search using keywords such as:++- Order number+- Customer email+- Customer name+- SKU++Simply enter your query and press **Enter** to return matching results.++You can also combine search with filters (described below) to further narrow down results.++## Date Filter++++You can filter orders by date to focus on a specific time period.++Click the date selector and choose a predefined range (e.g., Today, Last 7 Days) or set a custom date range to display only orders created within that timeframe.++## Sorting & Columns++Spree’s new table system allows you to customize and sort your order view.++### Sorting++++You can sort orders by clicking on the Sort dropdown above the table, and selecting the column you’d like to sort by (such as Order Number, Total, Payment State, etc.).++At the bottom of the dropdown, select whether you prefer Ascending or Descending order.++This is useful for:++- Viewing highest or lowest order totals+- Seeing newest or oldest orders first+- Grouping orders by payment or shipment status++### Column Customization++++You can also choose which columns are visible in your table view without the helpo of developers.++Open the column settings menu and select or deselect the columns you’d like to display. This allows you to tailor the view based on your workflow - for example, focusing on financial data, fulfillment status, or customer details.++## Advanced Filters++++Filters have been significantly improved and now support **operators** and **AND / OR grouping**, giving you much more control over how you refine results.++You can create filter groups using the following fields:++- Order Number+- Payment State+- Shipment State+- Total+- State+- First Name+- Last Name+- SKU+- Promotion++### Operators++Each filter condition also includes an operator, allowing you to define exactly how the value should be evaluated. Available operators include:++- equals+- does not equal+- greater than+- greater than or equal+- less than+- less than or equal+- is any of+- is none of+- is empty+- is not empty++For example:++- Total greater than 500+- Payment State is any of Paid, Refunded+- Promotion is not empty+- Shipment State does not equal Fulfilled++### Using AND / OR Groups++- **AND** conditions require all criteria to be met.+- **OR** conditions return results that match any of the selected criteria.++For example:++- Orders where **Payment State = Balance Due AND Shipment State = Ready**+- Orders where **Promotion = SUMMER2025 OR Promotion = VIPDISCOUNT**++This flexibility makes it much easier to identify specific subsets of orders for follow-up, reporting, or operational tasks.++By combining **search**, **date filters**, **sorting**, **column customization**, and **advanced filter groups**, you can quickly locate exactly the orders you need - no matter how large your order history becomes.diff --git a/docs/v5/user/products/cloning-products.mdx b/docs/v5/user/products/cloning-products.mdxnew file mode 100644index 0000000000..415d88e766--- /dev/null+++ b/docs/v5/user/products/cloning-products.mdx@@ -0,0 +1,39 @@+---+title: "Clone a Product"+description: "Learn how to clone a product in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/products/cloning-products"+---++If you need to create multiple products with similar details - such as color variants, seasonal versions, or items with the same structure - cloning an existing product can save you a lot of time. This is especially helpful when working with multi-variant products.++## How to Clone a Product++++1. Go to the **Products** tab in the admin and open the product you want to clone.+2. Click the **three-dot menu** in the top-right corner.+3. Select **Clone** from the dropdown.++You’ll be redirected to the product editor for the newly cloned product.++++### Cloning Behaviour++When cloning a product, most of the product fields are copied over, with a few key differences:++- **Name** changes to **COPY OF Name**+- **Slug** changes to **/copy-of-name**+- **Status** is set to **Draft** by default+- **Stock** quantity is reset to **0**++## Update the New Product++Now that the product has been cloned, you'll need to update the product details as needed (e.g., name, media, price, stock levels) to reflect the new product.++Remember to click **Update** at the top or bottom of the page to save your changes.++\+For help understanding the fields in the product editor, see [Create a Product](https://spreecommerce.org/docs/user/products/creating-products)++For help updating variant-specific info, see [Edit a Multi-Variant Product](https://spreecommerce.org/docs/user/products/editing-multi-variant-products)\ No newline at end of filediff --git a/docs/v5/user/products/creating-products.mdx b/docs/v5/user/products/creating-products.mdxnew file mode 100644index 0000000000..039c7dbc74--- /dev/null+++ b/docs/v5/user/products/creating-products.mdx@@ -0,0 +1,249 @@+---+title: "Create a Product"+description: "Step-by-step guide to creating a product in the Spree admin, including media, pricing, variants, inventory, shipping, and digital downloads."+canonical: "https://spreecommerce.org/docs/user/products/creating-products"+---++Adding products manually is a crucial part of managing any ecommerce store. Whether you're launching something new, setting up preorders, or testing a market-specific variant, Spree makes it easy to create fully-detailed products through a clean and structured editor.++This guide walks you through each section of the product editor, explaining what each field does and why it matters.++<Warning>+ Don’t forget to click Create at the bottom of the page before navigating away — changes aren’t saved automatically.+</Warning>++## Create a New Product++To get started, navigate to the **Products** tab of the admin dashboard.++++Click **New Product** in the top right corner to open the product creation form.++++## Name & Description++++++The first fields at the top of the product form let you enter:++- **Name:** Shown on product listing pages, the PDP, checkout.+- **Description:** Displayed on the product detail page. Supports rich formatting like bold text, headings, links, and images.++A good name and description helps customers understand what they're buying - they’re also used for SEO if no dedicated meta fields are set.++## Media++++This is where you can add visual media to your product. Click **Upload New Asset** to open the file importer.++++Once your chosen files have been uploaded, you can rearrange the images by dragging and dropping - the left most image is the main image used on product listings.++++To edit an image’s alt text, replace it, or delete it entirely, click on the image to open the edit form.++++<Note>+ You can also use the checkboxes to delete multiple images at once.+</Note>++## Availability & Status++++This section controls when and how your product appears on the storefront:++- **Status:**+ - **Active:** visible and purchasable+ - **Draft:** hidden from customers+ - **Archived:** stored in the admin, no longer available+- **Make Active At:** Schedule a future go-live date+- **Available On:** Set a public release date (commonly used for preorders)+- **Discontinue On:** Choose a date to automatically unpublish the product++These tools let you prepare seasonal drops, preorders, or time-limited products in advance.++## Categorization++++Organizing products properly helps with navigation and merchandising. Here you can add:++- **Taxonomies:** Assign categories, collections, or brands (e.g., Fashion → Women → Tops). Products will appear anywhere the taxon is used on the site.++ +- **Tags:** Use custom tags like Vegan, Eco-Friendly, or Summer Collection for filtering, related products, or smart merchandising logic.++ ++There’s no limit to the number of taxons or tags you can apply.++<Note>+ Taxonomies must be created in **Products → Taxonomies** before they can be assigned to products. Tags, on the other hand, can be created directly in the product editor.+</Note>++## Pricing++++This section controls how much your product sells for:++- **Amount:** The selling price shown on the storefront+- **Compare At Amount:** Optional field for showing a discounted or original price.++Setting a Compare At amount will add a crossed-out price and a Sale badge to the product wherever it appears on the storefront.++++If your store supports multiple currencies, you’ll see additional rows here to define localized pricing.++++<Note>+ Add or manage supported currencies in **Settings → Store Settings**.+</Note>++## Inventory++++This section lets you manage stock levels and tracking:++- **Track Quantity:** Enable this if you want to keep count of stock and prevent overselling.+- **Quantity:** Set available inventory for each stock location.+- **Continue Selling When Out of Stock:** Optional override that allows customers to purchase even if stock is zero.+- **SKU:** Internal identifier for managing stock. Not required, but helpful — must be unique per variant.+- **Barcode:** Used for scanning in warehouses, syncing with logistics providers, or POS systems. Supports ISBN, UPC, GTIN, etc.++<Note>+ If quantity tracking is enabled, stock is automatically reduced when orders are placed.+</Note>++## Variants++++If your product has multiple sizes, colors, or formats, use the Variants section. To add variants, first click **Add options like size or color** to open the variant form.++++Then, simply follow these steps to add variants:++1. Choose an **Option Name** (e.g., Size, Color)+2. Add **Option Values** (e.g., S, M, L)+3. Click **Done**+4. Add more option types if needed++<Note>+ You can add or manage Options under **Products → Options**.+</Note>++Once added, you'll see per-variant Price and Inventory fields so you can manage each combination independently.++++<Note>+ Keep naming consistent across products (e.g., use S, M, L everywhere - not Small, Medium, Large on some items and initials on others).+</Note>++## Shipping++++If your shipping methods rely on product size or weight, this section is critical.++- **Dimensions & Weight:** Enter the product’s width, height, depth, and weight.+ - These values can be used to calculate shipping costs automatically+- **Shipping Category:** Choose the category that determines shipping behavior.+ - E.g., assign Digital for downloadable products, or Heavy for oversized items.++<Note>+ You can change the default unit system (metric vs imperial) in **Settings → Store Details → Standards & Formats**.+</Note>++## Product Metafields++Product Metafields let you add custom data fields to a product beyond Spree's built-in fields — useful for technical specs, care instructions, supplier notes, or anything else specific to your catalog. For example, a clothing product might have a **Material** metafield set to "100% Organic Cotton," or an electronics product might have a **Voltage** metafield set to "110–240V."++See [<u>Product Metafields</u>](/v5/user/manage-products/product-metafields) to learn how to create metafield definitions and add values to your products.++## Tax++++Assign a tax category to the product, which determines how taxes are applied based on customer region and store settings. For example:++- Default Tax+- Tax Exempt+- Downloadable Goods++## Search Engine Listing++++This section allows you to control how the product appears in search engine results and on social media.++Click **Edit** to modify:++- **Meta Title:** The page title shown in search results+- **Meta Description:** Short summary shown beneath the title+- **Slug:** Controls the product’s URL. If not set, the product name is used (e.g., /black-hoodie)++## Digital Products++If you assign the **Digital** shipping category to a product, no physical fulfilment is required — but you'll also need to upload the file customers will receive after purchase.++Digital assets can be any downloadable file, most commonly:++- **PDFs** — ebooks, guides, certificates+- **ZIP archives** — software, templates, sample packs+- **Audio and video files** — courses, music, video content+- **License or activation keys** — delivered as a text file++Once purchased, customers can access their digital files from the order confirmation page, a link in their confirmation email, or their **My Account** dashboard.++To upload a digital asset:++1. In the product editor, click the *three-dot** menu in the top-right corner.+2. Select **Digital Assets** to open the digital assets management screen.+3. Click **New Digital Asset** to open the upload form.+4. Upload the file. If the product has multiple variants, also select which variant the asset should attach to.++### Download access and limits++Spree generates a unique digital link with a token for each purchased line item. You can restrict how customers use that link from your store's digital product settings:++- **Maximum downloads** - cap how many times the file can be downloaded per order (for example, 5).+- **Link expiry** - set how long the link remains valid after purchase (for example, 3 days).++When a customer exceeds either limit, the storefront returns an error and the file is no longer accessible from that link. Admins can resend the download email or regenerate the link from the order if needed.++### How customers receive the file++After an order is placed, customers can access their files in three ways:++- **Order confirmation page** - download links appear on the success page immediately after checkout.+- **Order confirmation email** - links are included in the email sent after purchase.+- **My Account dashboard** - logged-in customers can return to their account to re-download (subject to the limits above).++Internally, each download is served via `GET /api/v3/store/digitals/{token}`. The token alone authorizes the download — no API key or login is required — which is why download limits and expiry exist.++For more on the digital product model, see the [Digital Products](/use-case/digital-products/admin-capabilities) overview.++## Save Changes++Once you’ve filled out all the required and optional fields, scroll to the bottom and click Create to publish the product (or save it as a draft).++You can always return to this page to update or archive the product later.++## 3rd Party Products (Enterprise only)++If you’re running a multi-vendor marketplace with Spree Enterprise Edition, vendors will create or upload their own products during onboarding. You can still review and edit vendor-created products as needed.diff --git a/docs/v5/user/products/deleting-products.mdx b/docs/v5/user/products/deleting-products.mdxnew file mode 100644index 0000000000..87109babcf--- /dev/null+++ b/docs/v5/user/products/deleting-products.mdx@@ -0,0 +1,23 @@+---+title: "Delete a Product"+description: "Learn how to delete a product in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/products/deleting-products"+---++There may be times when you need to permanently remove a product from your catalog - for example, if it was added by mistake, duplicated, or no longer needed in your system.++Deleting a product removes it entirely from your store and the admin interface. However, this action is <u>not available</u> for products associated with any orders, whether completed or not.++<Note>+ If a product is linked to one or more orders, it cannot be deleted. In these cases, set the product’s **Status** to **Archived** instead. This removes it from the storefront while keeping it in the admin, making it clear to other team members that the product is discontinued or no longer active.+</Note>++## How to Delete a Product+++1. Go to the **Products** tab in the admin dashboard and open the product you want to delete.+2. Scroll to the bottom of the product editor.+3. Click the **Delete** in the bottom-right corner.+4. In the confirmation modal, click **OK** to confirm or simply press **Enter.**++Once confirmed, the product will be permanently removed from your store.\ No newline at end of filediff --git a/docs/v5/user/products/editing-multi-variant-products.mdx b/docs/v5/user/products/editing-multi-variant-products.mdxnew file mode 100644index 0000000000..1541a9ec0d--- /dev/null+++ b/docs/v5/user/products/editing-multi-variant-products.mdx@@ -0,0 +1,113 @@+---+title: "Edit a Multi-Variant Product"+description: "Learn how to edit a multi-variant product in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/products/editing-multi-variant-products"+---++Editing multi-variant products is a bit more involved than single-variant ones, since each variant can have unique details - such as pricing, stock levels, or media.++This guide will show you how to manage variant options, edit individual variants, and tailor settings for specific combinations.++## How to Edit a Multi-Variant Product++To get started, go to the **Products** tab in the admin dashboard, and click on the product you'd like to update to open the product editor.++++Scroll down to the **Variants** section where you should see all associated product variants.++++This section is where you can manage all settings related to the product’s variants, including options, pricing, inventory, and more.++## Options++++At the top of the **Variants** section, you’ll see the product's assigned **Options** (e.g., Color and Size) along with their respective values (e.g., White, Blue, S, M, etc.).++### Edit Options++++- To edit an Option, click the **Edit** button. You can:+ - Add or remove values (e.g., remove “XS” or add “L”)+ - Change the Option Name by selecting a new one from the dropdown+- To add another Option entirely, click **\+ Add another option** at the bottom.++Click **Done** to save your changes.++<Note>+ Changes here will automatically update the list of generated variants below.+</Note>++## List of Variants++++Beneath the **Options** editor, you’ll see a list of product variants generated by the Option Value combinations.++For example, 2 colors × 3 sizes = 6 total variants.++Each variant row includes fields for:++- **Price**+- **Quantity**+- **Edit** button (for advanced settings)++You can adjust price and stock directly in this view by entering new values into the respective fields.++## Editing Variants++In some cases, variants may differ significantly, whether it be by size, weight, barcode, or even media. For these situations, it’s helpful to manage them individually.++To edit a variant, click **Edit** to open the **variant editor**.++<Warning>+ If you’ve made changes to the main product, be sure to click **Update** before editing a variant. Otherwise, those changes may be lost when switching views.+</Warning>++++Here you can modify the following fields:++- **SKU**+- **Barcode**+- **Tax Category**+- **Discontinue On**+- **Dimensions**+- **Weight**+- **Price**+- **Compare At Amount**+- **Quantity**+- **Backorderable**+- **Media**++Remember to click **Update** to save any changes you've made.++## Variant-Specific Media++++You can upload images specific to each variant to improve the product detail page experience.++For example, if you sell a shirt that's available in White and Blue, upload white-shirt images to the White variants and blue-shirt images to the Blue variants.++This ensures that when a customer selects a variant on the storefront, the most relevant images are shown automatically.++## Deleting Variants++++Since not all combinations of color, size, etc., may be valid for sale, you may wish to delete some variants entirely.++If there are variants you don’t offer:++1. Check the box next to the unwanted variant(s)+2. Click **Delete selected**++Deleting a variant will remove it's row from the list. To undo this, reconfigure the **Options** and then click **Update** at the top/bottom of the page.++## Save Changes++Whether you're editing the main product or a variant, always remember to click **Update** to save your changes.\ No newline at end of filediff --git a/docs/v5/user/products/editing-products.mdx b/docs/v5/user/products/editing-products.mdxnew file mode 100644index 0000000000..f75070d063--- /dev/null+++ b/docs/v5/user/products/editing-products.mdx@@ -0,0 +1,32 @@+---+title: "Edit a Product"+description: "Learn how to edit a product in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/products/editing-products"+---++There are many reasons you might need to update a product - whether it’s to correct a mistake, respond to new inventory or pricing, or simply adjust how it appears on the storefront. Common examples include:++- Updating the price+- Editing the name or description+- Hiding the product from the storefront+- Adding new images+- Changing or adding categories and tags++Whatever the reason, editing a product is straightforward and can be done at any time.++## How to Edit a Product++++1. Go to the **Products** tab in the admin dashboard and click on the product you want to update.+2. This opens the product editor, where you can modify any existing field or fill in previously empty ones.+3. Make your changes as needed across the different sections (e.g., Pricing, Media, Inventory, etc.)+4. When finished, click **Update** at the top or bottom of the page.++You’ll see a confirmation message once the changes have been successfully saved.++++To learn more about the product editor and how each section works, see: [Create a Product](https://spreecommerce.org/docs/user/products/creating-products)++To update variant-specific details for products with multiple options (e.g., size, color), see: [Edit a Multi-Variant Product](https://spreecommerce.org/docs/user/products/editing-multi-variant-products)\ No newline at end of filediff --git a/docs/v5/user/promotions/create-a-promotion.mdx b/docs/v5/user/promotions/create-a-promotion.mdxnew file mode 100644index 0000000000..b121590ce4--- /dev/null+++ b/docs/v5/user/promotions/create-a-promotion.mdx@@ -0,0 +1,146 @@+---+title: "Create a Promotion"+description: "Learn to how to create and configure promotions in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/promotions/create-a-promotion"+---++Promotions are a powerful way to drive conversions, reward loyal customers, and support marketing campaigns. Whether you’re offering discounts, free shipping, or bonus products, Spree’s promotion engine gives you fine-grained control over when a promotion applies and what it does.++This guide covers how to create and configure a promotion in Spree. Detailed explanations of individual rules and actions are covered in separate articles.++## Create a New Promotion++To create a promotion, navigate to the **Promotions** tab in the admin dashboard.++++Click **New Promotion** in the top-right corner, to open the Promotion creation form.++++Here you can do the following:++### Choose a Promotion Type++++When creating a promotion, you’ll first select how it’s applied:++- **Coupon Code** - The promotion is applied only when a valid code is entered at checkout. You can choose between:+ - **Single Code** - one shared code (e.g. SUMMER10)+ - **Generated Codes** - automatically generate unique codes+ - Optional prefix (e.g. VIP-)+ - Set how many codes should be generated+ - Unique codes can be downloaded for easier distribution+- **Automatic** - The promotion is applied automatically at checkout once its conditions are met. No coupon code required.+ - This is ideal for sitewide sales, free shipping offers, or first-time customer discounts.++### Configure Promotion Settings++++Next, configure the promotion’s availability and limits:++- **Usage Limit** - Maximum number of times the promotion can be used (optional).+- **Starts At** - Date and time when the promotion becomes active.+- **Expires At** - Date and time when the promotion is no longer valid.++Once these fields are set, click **Create**, the form will update, and you can now configure the rules and actions for the promotion.++## Configure Rules & Actions++++After creating the promotion, you’ll be redirected to the main configuration screen. This is where the actual logic of the promotion is defined.++You’ll see two main sections:++- **Rules** - determine when the promotion applies+- **Actions** - determine what happens when it applies++<Warning>When adding a rule or action, changes are saved immediately.</Warning>++There are also two side panels that let you update:++- Promotion details (name, code)+- Promotion settings (usage limits, start/end dates)++### Promotion Rules (Conditions)++++Rules define eligibility. You can combine multiple rules using:++- **Match any** - at least one rule must be satisfied+- **Match all** - all rules must be satisfied++Available rule types include:++- **Currency** - Order must be in a specific currency+- **Country** - Shipping address must be in a specific country+- **Item Total** - Order total meets defined thresholds+- **Product(s)** - Order contains specific products+- **User** - Available only to specific customers+- **First Order** - Customer’s first purchase only+- **User Logged In** - Requires the customer to be logged in+- **One Use Per User** - Limits redemption to once per customer+- **Taxon(s)** - Order contains products from selected taxons+- **Option Value(s)** - Order contains products with specific option values++Rule behavior and configuration details are covered in [<u>Promotion Rules</u>](https://spreecommerce.org/docs/user/promotions/promotion-rules).++### Promotion Actions (Effects)++++Actions define what the promotion does once its rules are satisfied.++Available actions include:++- **Create whole-order adjustment** - Applies a discount to the entire order.+- **Create per-line-item adjustment** - Applies discounts to individual line items.+- **Create line items** - Automatically adds products (e.g. gifts) to the cart.+- **Free shipping** - Makes all shipments for the order free.++Each action supports one or more calculators (e.g. flat rate, percentage, tiered discounts). These are covered in detail in [<u>Promotion Actions</u>](https://spreecommerce.org/docs/user/promotions/promotion-actions).++## Promotion Ready to Use++Once you’ve added the promotion’s rules and actions, it’s ready to be used by customers.++- **Automatic promotions** will apply at checkout as soon as the conditions are met.+- **Coupon code promotions** can be redeemed when customers enter the code during checkout.++How you market, distribute, or communicate the promotion (e.g., email campaigns, banners, social media, influencer codes) is entirely up to you and your team.++## Common Promotion Examples++**10% Off with a Coupon Code**++- Type: Coupon Code (single code)+- Rule: None (or minimum order total)+- Action: Whole-order adjustment → 10% discount++**Free Shipping Over \$50**++- Type: Automatic+- Rule: Item total ≥ \$50+- Action: Free shipping++**First-Time Customer Discount**++- Type: Automatic+- Rules: First order, User logged in+- Action: Whole-order adjustment → flat or percentage discount++**Buy from a Category, Get a Discount**++- Type: Automatic+- Rule: Taxon(s)+- Action: Per-line-item adjustment++**Advanced Example: VIP Coupon for EU Customers**++- Type: Coupon Code (generated unique codes with prefix)+- Rules: User, One use per user, Currency+- Action: Whole-order adjustment with tiered percentage calculatordiff --git a/docs/v5/user/promotions/gift-cards.mdx b/docs/v5/user/promotions/gift-cards.mdxnew file mode 100644index 0000000000..97733491fa--- /dev/null+++ b/docs/v5/user/promotions/gift-cards.mdx@@ -0,0 +1,104 @@+---+title: "Gift Cards"+description: "Learn how to create individual or bulk gift cards in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/promotions/gift-cards"+---++Gift cards allow customers (or recipients) to redeem a prepaid balance at checkout. In Spree, you can create single gift cards for specific customers or generate batches of codes for broader distribution.++To get started, navigate to **Promotions → Gift Cards** in the admin dashboard.++++Click **New Gift Card** in the top right corner.++++You’ll be prompted to choose between:++- **Gift Card** (single code)+- **Gift Card Batch** (multiple codes generated at once)++## Create a Single Gift Card++++Selecting **Gift Card** opens the creation form.++Complete the following fields:++- **Email (optional)** - Assign the gift card to a specific customer email, or leave blank to create an unassigned code.+- **Code** - Leave blank to auto-generate a unique code, or enter one manually.+- **Amount** (required) - The value of the gift card.+- **Currency** (required) - The currency the card should be issued in.+- **Expires At** - Optional expiration date. Leave blank for a non-expiring card.++Click **Create** to issue the gift card. It will appear in the Gift Cards table and can be redeemed using the code at checkout.++## Create a Gift Card Batch (Bulk Generation)++++Selecting **Gift Card Batch** allows you to generate multiple codes at once.++The form includes the same core fields as a single gift card (excluding the Customer field), plus:++- **Prefix** - Adds a custom prefix to each generated code (e.g., HOLIDAY-, VIP-).+- **Codes Count** (required) - The total number of gift card codes to generate.++Spree will automatically create the specified number of unique codes.++After clicking **Create**, all generated gift cards will be added to the Gift Cards table.++## Manage & Export Gift Cards++++Once created, gift cards appear in the main table view under **Promotions → Gift Cards**.++The table displays key information for each card, including:++- Code+- Original amount+- Amount of credit used+- Currency+- Expiration date+- Assigned customer (if any)++This makes it easy to monitor usage and track remaining balances.++### Edit a Gift Card++++To edit a gift card:++1. Click on the gift card from the table+2. In the **Settings** section, click **Edit**+3. Update the necessary fields+4. Click **Save**++### Delete a Gift Card++++To delete a gift card:++1. Open the gift card+2. Click the **three-dot menu** in the top-right corner+3. Select **Delete**++### Export Gift Cards++You can also:++- Use **Filters** to narrow results+- Sort columns+- Customize visible columns+- Click **Export** to export filtered records to CSV++This is especially useful when distributing bulk-generated codes for marketing campaigns, partnerships, or seasonal promotions.++## How to Redeem Gift Cards++Customers can redeem a gift card at checkout by entering the gift card code into the Promotion field before completing their purchase.diff --git a/docs/v5/user/promotions/promotion-actions.mdx b/docs/v5/user/promotions/promotion-actions.mdxnew file mode 100644index 0000000000..cffe17c3e1--- /dev/null+++ b/docs/v5/user/promotions/promotion-actions.mdx@@ -0,0 +1,91 @@+---+title: "Promotion Actions"+description: "Learn how to use promotion actions in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/promotions/promotion-actions"+---++Promotion actions define what happens when a promotion is applied. Once a promotion’s rules are met (if any), its actions are either triggered automatically at checkout or when applying the coupon code on checkout.++Actions can apply discounts, add items to the cart, or make shipping free - and each action can be customized further using various calculators.++## Available Promotion Actions++Here are the actions you can apply to a promotion in Spree:++### Create Whole-Order Adjustment++Applies a discount to the entire order total.++This is ideal for:++- Sitewide sales (e.g., 10% off everything)+- Cart value promotions (e.g., \$20 off orders over \$100)++### Create Per-Line-Item Adjustment++Applies a discount individually to eligible line items in the order.++This is best used when:++- You want to discount only certain products or product groups+- You’re combining with Product, Taxon, or Option Value rules++Each qualifying item will receive a proportional discount based on the calculator settings.++### Create Line Items++Automatically adds products to the customer’s cart when the promotion applies.++Common uses:++- “Buy X, get Y free” campaigns+- Gift-with-purchase offers+- Sample distribution++You’ll be able to:++- Select the variant(s) to add+- Set the quantity+- Combine with other actions to set price rules (e.g., set to free or discounted)++### Free Shipping++Makes all shipments in the order free.++Best used when:++- Offering free shipping above a certain threshold+- Running promotional periods with free delivery++This action zeroes out the shipping cost - no calculator needed.++## Configuring Actions with Calculators++Most actions (except Free Shipping) support the use of calculators to control how the discount is applied.++The available calculators are as follows:++- **Flat Rate** - Apply a fixed discount amount (e.g., \$10 off)+- **Flat Percent** - Apply a percentage discount (e.g., 15% off)+- **Flexible Rate** - Apply a base discount + per-item amount+- **Tiered Flat Rate** - Different flat discounts based on order value or item count+- **Tiered Percent** - Varying percentage discounts based on thresholds++Example: A tiered flat rate could apply \$5 off orders over \$50, and \$10 off orders over \$100.++You'll choose a calculator when you add the action. The fields shown will depend on the calculator type selected.++## Notes on Behavior++- You can add multiple actions to the same promotion (e.g., discount + free shipping).+- Changes to actions are saved immediately after adding or updating them.+- Actions apply only after all rules (if any) are satisfied.++## Example Use Cases++| **Goal** | **Action(s)** | **Calculator** |+| :---------------------------------- | :---------------------------------------- | :------------------------------------------ |+| \$10 off entire order | Whole-order adjustment | Flat Rate |+| 20% off selected products | Per-line-item adjustment | Flat Percent |+| Add a free tote bag on orders \$50+ | Create line items, Whole-order adjustment | Flat Rate (set to price of added line item) |+| Free shipping on all orders | Free shipping | – |diff --git a/docs/v5/user/promotions/promotion-rules.mdx b/docs/v5/user/promotions/promotion-rules.mdxnew file mode 100644index 0000000000..9f99321804--- /dev/null+++ b/docs/v5/user/promotions/promotion-rules.mdx@@ -0,0 +1,131 @@+---+title: "Promotion Rules"+description: "Learn how to use promotion rules in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/promotions/promotion-rules"+---++Promotion rules define the conditions that must be met for a promotion to be applied. Spree gives you full control over when a promotion should be eligible - whether it’s based on the order total, customer group, specific products, or a user’s login status.++Each promotion can have multiple rules, and you can choose whether all rules must match (match all) or any rule must match (match any).++## Rule Match Policies++At the top of the Rules section in the promotion editor, you’ll see the Match Policy toggle:++- **Match all** - All rules must be satisfied for the promotion to apply.+- **Match any** - Only one rule needs to be satisfied.++This gives you flexibility to fine-tune how strict or lenient the promotion conditions should be.++## Available Promotion Rules++Below is a list of all rule types currently supported in Spree, along with when and why you might use them.++### Item Total++Applies the promotion only if the order total meets a specific threshold.++Use this when:++- Offering discounts above a certain spend (e.g. \$50+ orders)+- Creating tiered incentives for larger carts++### Country++Limits the promotion to customers whose shipping address is in a specific country.++Useful for:++- International promotions+- Localized campaigns (e.g., “Free shipping in the US”)++### Currency++Applies the promotion only to orders in a specific currency.++Use this if:++- You're running different promotions in different markets+- You want to avoid coupon misuse across regional stores++### Product(s)++Limits the promotion to orders that include one or more specific products (variants).++Perfect for:++- Targeted discounts on select SKUs+- Bundling or cross-sell offers++### Taxon(s)++Applies when the order includes products belonging to specific taxons (categories, collections, etc.).++Ideal for:++- Category-wide promotions (e.g., “25% off all shoes”)+- Seasonal or campaign-specific collections++### Option Value(s)++Triggers when products in the cart have a specific option value (e.g., color, size, material).++Use cases:++- Color-specific clearance sales+- Size-limited inventory promos++### User++Applies only to specific customers.++This is useful for:++- VIP offers+- Manually targeting customers (e.g. after support tickets, outreach)++### First Order++Applies only if the promotion is being used on a customer’s first-ever order.++Great for:++- Welcome offers+- Signup conversion boosts++### User Logged In++Applies only when the customer is logged in.++Use this to:++- Encourage account creation+- Hide promotions from guest checkout users++### One Use Per User++Restricts the promotion so that each user can only use it once.++Helps prevent abuse and maintain exclusivity.++### Customer Group++Limits the promotion to customers belonging to a specific Customer Group.++Perfect for:++- Wholesale or B2B-only promotions+- Segment-specific campaigns (e.g., “Early Access” or “Loyal Customers”)++Customer Groups are created under [<u>Customers → Customer Groups</u>](https://spreecommerce.org/docs/user/customers/customer-groups).++## Example Use Cases++| **Goal** | **Rule(s) to Use** |+| :------------------------------------ | :------------------------------ |+| \$10 off first order only | First Order + User Logged In |+| 20% off selected category | Taxon(s) |+| Exclusive deal for logged-in VIPs | User Logged In + Customer Group |+| Free shipping to U.S. only | Country (US) |+| Discount on red-colored items | Option Value(s) → Color: Red |+| Welcome promo limited to one-time use | First Order + One Use Per User |diff --git a/docs/v5/user/returns/returns-processing.mdx b/docs/v5/user/returns/returns-processing.mdxnew file mode 100644index 0000000000..fed7d8c497--- /dev/null+++ b/docs/v5/user/returns/returns-processing.mdx@@ -0,0 +1,137 @@+---+title: "Returns Processing"+description: "Learn how to process returns in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/returns/returns-processing"+---++Spree supports native returns processing, giving you full control over how refunds, exchanges, and restocking are handled directly from the admin dashboard. The workflow is designed to be flexible, with clear steps for managing each stage of the return process.++This guide walks you through the full lifecycle of a return: from authorization, to customer return, to final reimbursement.++## 1) Create a Return Authorization (RA)++Returns are initiated from the order, not from the Returns tab, so navigate to the Orders tab and open the relevant order.++++<Note>+ Alternatively, find the customer in the Customers tab and access their order from there.+</Note>++Click the three-dot menu in the top-right corner and select **New Return Authorization**.++++This will open the Return Authorization form.++++Here you’ll see a table of line items from the order. For each item, configure the following:++- **Include in RA**: check the box to include this item in the return+- **Product**: name and variant (read-only)+- **Status**: shipment status (e.g., "shipped", read-only)+- **Charged**: amount originally charged to the customer+- **Return Quantity**: set how many units should be returned (0 if not returning)+- **Pre-tax Refund Amount**: amount to be refunded per item+- **Reimbursement Type**: choose from: Exchange, Store Credit, Credit, Original Payment+- **Exchange for**: if Exchange is selected, choose the replacement variant from the dropdown++Below the table, you’ll see a dynamic refund summary showing the Total Pre-Tax Refund amount (e.g., $35.00).++At the bottom of the form complete the additional fields:++- **Location**: stock location the item should be returned to (required)+- **Reason**: select an RMA reason (required)+- **Memo**: optional internal note++Click **Create** to finalize the Return Authorization.++You’ll be redirected back to the order overview, where a Return Authorizations section will now appear under the Shipments section. You can edit the RA at any time.++++The RA will also now be listed in the **Returns → Return Authorizations** tab.++++## 2) Create a Customer Return++With an RA in place, you're ready to log the return of the physical item.++From the same order overview page, click the three-dot menu again and select **New Customer Return**.++++This will open the Customer Return form.++++The form lists each item from the order. For each item, configure:++- **Include in return**: check if the item has been returned+- **Product**: name and variant (read-only)+- **SKU**: stock keeping unit (read-only)+- **Pre-tax Amount**: non-zero if part of the RA, 0 if not included (read-only)+- **Exchange for**: variant selected for exchange (if applicable) (read-only)+- **Resellable**: check if the item can be restocked; unchecked items won’t be returned to inventory++Below the table, select:++- **Location**: confirm the stock location the items are being returned to++Click **Create** to finalize the Customer Return.++You’ll then be returned to the order overview page again, and a new Customer Returns section will appear above the Return Authorizations section.++++The return will also now be visible in the Returns tab and can be edited from either location.++++## 3) Reimburse the Customer++Once a customer return has been logged, you can process the refund or exchange.++In the Customer Returns section, click the three-dot menu and select **Create Reimbursement**.++++This will create the reimbursement immediately and redirect you to the reimbursement form.++++Here you can review the items to be reimbursed, and override the reimbursement type or the exchange variant if necessary (e.g., reimburse with store credits instead of the original payment).++Click **Reimburse** to finalize the return process:++- If it’s a refund, the customer will be reimbursed via the selected method.+- If it’s an exchange, a new shipment will be created on the order and can be fulfilled like any other shipment.++++### Alternative Method++If you’d like to review the Customer Return before reimbursing the customer, you can instead select **Edit** from the three-dot menu, or just click on the Customer Return itself.++This will redirect you to a Customer Return summary that includes a Reimbursements section.++++This form displays:++- Customer name+- Order number+- Reimbursement status+- Pre-tax total+- Line item details:+ - Product+ - Amount+ - Reimbursement Type+ - Exchange For+ - Acceptance Errors++At the bottom of the page you’ll find the **Reimbursements** section.++Simply click **Create Reimbursement** and follow the steps outlined previously.\ No newline at end of filediff --git a/docs/v5/user/security.mdx b/docs/v5/user/security.mdxnew file mode 100644index 0000000000..da655b1c01--- /dev/null+++ b/docs/v5/user/security.mdx@@ -0,0 +1,153 @@+---+title: "Enterprise Edition Security Overview"+sidebarTitle: "Enterprise Edition Security Overview"+description: "Learn how Spree Enterprise is built to meet the highest standards of data protection and risk management."+canonical: "https://spreecommerce.org/docs/user/security"+---++Spree Commerce and its Enterprise Edition are engineered with robust security practices designed to meet the expectations of enterprise customers performing formal security reviews aligned with **SOC 2 Type 2** and **ISO/IEC 27001** standards.++This document summarizes Spree’s security principles, development practices, infrastructure protections, and data-handling safeguards, providing assurance for procurement teams, risk assessors, and compliance auditors.++## 1. Secure Software Development Lifecycle (SDLC)++Our Secure Software Development Lifecycle (SDLC) ensures that every Spree Commerce release - Community or Enterprise - is developed, tested, and maintained following industry best practices.++### Governance and Oversight++- Managed directly by the CTO and senior leadership.+- Regular internal and external code reviews ensure continuous improvement.+- Third-party penetration testing to identify and mitigate security weaknesses early.++### Secure Development Practices++- Compliance with **OWASP Top 10** and **Ruby on Rails security guidelines** to prevent injection, CSRF, XSS, and mass-assignment vulnerabilities.+- All code undergoes **peer review** and **CTO approval** before merging.+- Dependencies are automatically updated using **GitHub Dependabot** or **GitLab Dependency Scanning**.+- **SAST**, **DAST**, and **SCA** scanning.++### Vulnerability Management & Incident Response++- Vulnerabilities are triaged by severity, ensuring critical issues are addressed immediately.+- Customers receive proactive notifications for relevant security updates.+- Incident response includes identification, containment, mitigation, and transparent communication.++### Data Protection++- All customer data is encrypted **in transit (TLS)** and **at rest (AES-256)**.+- Access control follows **least-privilege principles**.++## 2. Security-by-Design (Ruby on Rails Foundation)++Spree API is built on **Ruby on Rails**, a framework known for its strong “security-by-default” architecture. Rails powers global companies like Shopify, GitHub, Airbnb, Kickstarter, and Square—proving its enterprise readiness.++### Core Security Features++- **Injection Prevention**: ORM layer prevents SQL injection via parameterized queries.+- **CSRF Protection**: Rails automatically embeds authenticity tokens in forms to prevent cross-site request forgery.+- **XSS Mitigation**: Built-in HTML escaping and sanitization in views.+- **Strong Parameters**: Whitelists input attributes to prevent mass assignment.+- **Session & Cookie Security**: Signed, encrypted cookies and session management by default.++These features make security intrinsic to Spree’s architecture—not an afterthought.++## 3. PCI Compliance++Spree Commerce **does not store or process payment card data**. Instead, it integrates with **PCI-DSS compliant processors** (e.g., Stripe, Adyen).++- Only **encrypted payment tokens** are stored to link users with payment profiles in the processor’s system.+- For convenience, Spree retains limited metadata (card type, last four digits, expiry date) to enhance UX without exposing sensitive data.+- To satisfy PCI requirements **6.4.3** and **11.6.1**, we recommend using **Cloudflare PageShield** for client-side integrity monitoring, ensuring protection against form-jacking or malicious scripts.++## 4. Production Security++Spree’s production environments are recommended to be secured using modern infrastructure and trusted third-party services, for example:+- **PCI-compliant payment processors** (Stripe, Adyen)+- **Cloudflare**: DDoS protection, WAF, rate limiting, bot mitigation+- **GitHub/GitLab**: Source integrity, dependency scanning, vulnerability alerts+- **Strict change management** via Git-based workflows and CI/CD validation+- **Automated backups** with reliable recovery+- **Continuous monitoring** and logging for audit readiness++## 5. Authentication, SSO, and MFA++Spree supports **modern authentication mechanisms** for both the storefront and admin dashboard.++### Built-in Security++- Secure session handling, password hashing (bcrypt), and rate-limited login attempts.+- Role-based access control with least privilege enforced.++### SSO & MFA Integrations++- **Admin Dashboard Single Sign-on**: Integrates with Okta, Auth0, Azure AD, Google Workspace, etc.+- **Storefront Social Login**: Supports OAuth, OpenID Connect, and social logins (Google, Facebook, Apple).+- **MFA**: Can be enforced at the identity provider level or through custom add-ons.++## 6. Enterprise Edition Security Enhancements++The **Spree Commerce Enterprise Edition** includes additional enterprise-grade security and governance capabilities, among others:+- **Data Encryption**: Full encryption in-transit (TLS 1.2+) and at-rest (AES-256).+- **Single Sign-On (SSO)**: Optional integration for centralized identity management.+- **Granular Roles & Permissions**: Fine-grained access control across admin and API endpoints.+- **Audit Trail**: Every admin action is logged and reviewable for compliance audits.+- **Custom Hosting Support**: Enterprise customers can deploy Spree in ISO 27001 or SOC 2 compliant hosting environments (Render.com, AWS, GCP, Azure).++## 7. Compliance Alignment (SOC 2 / ISO 27001)++While Spree Commerce is a self-hosted platform—meaning its overall security depends on each customer’s infrastructure, configuration, and operational practices—it cannot itself be formally certified under SOC 2 or ISO 27001. However, its security controls are closely aligned with these standards and modeled on equivalent best-practice frameworks.++### Control Domains Alignment+| **Domain** | **Practice** |+| :----------------- | :------------------------------------------------------------------------- |+| Security | Access controls, vulnerability management, encryption, secure SDLC |+| Availability | High availability design, backup and disaster recovery |+| Confidentiality | Encryption of data, least-privilege access, NDAs |+| Integrity | Code reviews, CI/CD with automated testing |+| Privacy | Data minimization, no storage of payment or personal card data |++### Security Testing++- **Penetration testing** and **vulnerability assessments** performed before major releases.+- **Static and dynamic scanning** across code and infrastructure.+- **Annual independent third-party testing** (available for Enterprise customers under NDA).++### Business Continuity and Disaster Recovery++- Regular **offsite encrypted backups** with retention policies.+- **Disaster Recovery (DR)** procedures tested annually.+- **RTO/RPO** objectives designed to maintain service continuity and data integrity.++## 8. Transparency and Open Source Assurance++Spree’s open-source transparency is a unique security advantage:+- Publicly reviewable source code eliminates supply-chain opacity.+- Rapid community-driven identification and patching of vulnerabilities.+- Optional enterprise-only repositories provide controlled, hardened distributions.++## 9. Continuous Improvement++Security is never static. Spree maintains an evolving program of **policy reviews**, **training**, and **threat intelligence** updates to anticipate new risks. Lessons learned are integrated back into the SDLC to continuously strengthen the platform.++## 10. Enterprise Support++The **Spree Commerce Enterprise Edition** includes access to **Premium Support**, a partnership-level service designed to enhance **security**, **compliance**, **performance**, and **innovation**.++Premium Support provides direct access to the Spree core engineering team offering **priority assistance** covering, among others:+- **Security & compliance** – proactive patching, vulnerability guidance, and configuration reviews.+- **Performance & reliability** – optimization of caching, scaling, and infrastructure.+- **Custom development & integrations** – secure enhancements and system interconnections.+- **Continuous improvement** – upgrades aligned with the Spree roadmap and underlying software versions.++This ensures enterprise customers remain **secure, compliant, and high-performing** while continuously evolving their digital commerce environments.++## Get Started++<Columns cols={2}>+ <Card title="Book a Demo" icon="eye" href="https://getvendo.com/book-a-demo/" cta="Click here">+ Schedule a demo to explore the platform and get your questions answered+ </Card>+ <Card title="Ask for Pricing" icon="dollar-sign" href="https://spreecommerce.org/get-started/" cta="Click here">+ See Enterprise pricing for your use case+ </Card>+</Columns>diff --git a/docs/user/settings/checkout.mdx b/docs/v5/user/settings/checkout.mdxsimilarity index 93%rename from docs/user/settings/checkout.mdxrename to docs/v5/user/settings/checkout.mdxindex 261655ca37..9fb8583826 100644--- a/docs/user/settings/checkout.mdx+++ b/docs/v5/user/settings/checkout.mdx@@ -1,6 +1,7 @@---title: "Checkout"description: "Learn how to add a checkout message and enable or disable guest checkout."+canonical: "https://spreecommerce.org/docs/v5/user/settings/checkout"---In Spree, you can easily modify certain checkout settings directly from the dashboard - no developers needed. This gives you more control over the customer experience and lets you adapt quickly to your store’s needs.diff --git a/docs/v5/user/settings/emails.mdx b/docs/v5/user/settings/emails.mdxnew file mode 100644index 0000000000..eae4d4399b--- /dev/null+++ b/docs/v5/user/settings/emails.mdx@@ -0,0 +1,33 @@+---+title: "Emails"+description: "Configure how your store communicates with customers via email."+canonical: "https://spreecommerce.org/docs/user/settings/emails"+---++Email communication is a key part of building trust with your customers. From order confirmations to support inquiries, making sure your emails are professional and come from the right addresses helps reinforce your brand and ensures important messages reach the right people.++To configure email settings, navigate to the Emails tab of the Settings menu.++++## Logo for Emails++++Here you can upload a logo that will appear in all automated email notifications (e.g. order confirmations, shipment tracking). Simply select the file you wish to upload.++Note: We recommend using a transparent PNG or JPEG for best results.++## Email Addresses++++Here you can set the email addresses that will be used for various purposes by your business:++- **Mail from address**: The email address used as the sender for all outgoing store emails.+- **Customer Support Email**: This will be shown in your store’s footer so customers know how to reach you.+- **New Order Notifications Email**: Want to be notified every time an order is placed? Enter the email address where those alerts should go.++## Saving Changes++After making any updates, click Update at the bottom of the page to save your email settings, otherwise any changes you’ve made will not be saved.\ No newline at end of filediff --git a/docs/v5/user/settings/locations.mdx b/docs/v5/user/settings/locations.mdxnew file mode 100644index 0000000000..997d270fd0--- /dev/null+++ b/docs/v5/user/settings/locations.mdx@@ -0,0 +1,45 @@+---+title: "Stock Locations"+description: "Learn how to create and manage stock locations in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/settings/locations"+---++For large businesses with multiple warehouses, the ability to add multiple stock locations is essential for efficiently managing inventory across different regions.++It ensures accurate stock tracking, optimizes order fulfillment, and enables faster shipping by routing orders from the nearest warehouse.++To set up and manage stock locations, navigate to **Settings → Locations**.++++## Add a New Location++To add a new Location, click on **New Stock Location** in the top right corner. This will open the Location creation form.++++Simply enter a name, company name, the address, and (optionally) a phone number, and click then click **Create** at the bottom of the page to create the Location.++The new Location will now be added to your list of stock locations.++++## Edit a Location++To edit a Location, simply click **Edit** on the right-hand side of the Location’s row, and update the information as necessary.++## Set a Default Location++To set your default Location, click the **three-dot menu** on the right-hand side of the Location’s row and select **Mark as default** from the menu.++++## Delete a Location++To delete a Location, click **Edit** on the right side of the Location’s row to open the Location edit form, and click **Delete** at the bottom of the page.++++The Location will then be removed from your list of stock locations.++Congratulations, you now know how to create, edit, and delete stock locations!diff --git a/docs/v5/user/settings/marketplace.mdx b/docs/v5/user/settings/marketplace.mdxnew file mode 100644index 0000000000..8b820cf2a7--- /dev/null+++ b/docs/v5/user/settings/marketplace.mdx@@ -0,0 +1,54 @@+---+title: "Marketplace Configuration"+description: "Learn how to configure marketplace-wide settings for your multi-vendor marketplace in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/settings/marketplace"+---++<Warning>Marketplace settings are only available in Spree Enterprise Edition with the multi-vendor module enabled.</Warning>++The Marketplace settings page is the central place to configure how vendors operate on your marketplace by default. It's where you set the default commission rate new vendors will be invited under, how often vendors get paid, what merchants see when they install your Shopify app, and the terms of service every vendor agrees to. Most of these defaults can be overridden at a more granular level later (per vendor, category, or product), so think of this page as setting the baseline that everything else builds on.++To configure marketplace settings, navigate to **Settings → Marketplace** in the admin dashboard.++++## Vendor Commission Rate++This is the default percentage of each sale that your marketplace retains from a vendor's revenue. It applies to all newly invited vendors and can be overridden later per vendor, per category-vendor pairing, or per individual product.++- **Commission Rate** - the percentage taken from each sale. Used as the default for all newly invited vendors.++<Warning>Changing this value only affects newly invited vendors. Existing vendors keep their current commission rate — to update an existing vendor's rate, edit it from their vendor profile.</Warning>++## Vendor Payouts++This setting controls how frequently vendors can receive payouts through their Stripe dashboard. Vendors can choose to follow the marketplace default or set their own schedule from their vendor profile.++- **Preferred Vendor Payouts Schedule Interval** - how often vendors are paid by default.+ - Daily+ - Weekly+ - Bi-weekly+ - Monthly++<Note>Changing this option also updates the payout schedule for any existing vendors whose schedule is set to **Use marketplace default interval**. Vendors who have a specific schedule set won't be affected.</Note>++## Shopify App++If your marketplace uses the Shopify integration to onboard Shopify vendors, this image is displayed to Shopify merchants when they install your app. A clear, branded image helps vendors recognize the marketplace they're connecting to.++- **Upload New Media** - the image shown on the Shopify install screen.+ - **Recommended size:** 600 × 300 pixels.++<Note>For more on the broader Shopify vendor onboarding flow, see [<u>Shopify Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-shopify).</Note>++## Vendor Terms of Service++The terms of service displayed to vendors when they accept their invitation to join the marketplace. Vendors must agree to these terms before they can complete onboarding. The editor supports rich formatting including headings, bold, italic, links, lists, quotes, and code blocks.++- **Vendor Terms of Service** - the full terms vendors must agree to at invitation time.++<Note>Updating the terms doesn't require existing vendors to re-accept — only vendors invited after the change will see the new version at sign-up.</Note>++## Saving Changes++After making any updates, click **Update** at the bottom of the page to save your changes, otherwise any changes you've made will not be saved.diff --git a/docs/v5/user/settings/markets.mdx b/docs/v5/user/settings/markets.mdxnew file mode 100644index 0000000000..b2d083e1f4--- /dev/null+++ b/docs/v5/user/settings/markets.mdx@@ -0,0 +1,76 @@+---+title: "Markets"+description: "Learn how to create and manage markets in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/settings/markets"+---++import { Since } from '/snippets/since.mdx';++<Since version="5.4" />++Markets allow you to define distinct shopping experiences for different regions or customer+segments — each with its own currency, language, and tax settings. When multiple markets are+configured, customers can switch between them on the storefront to see prices and content in+their preferred currency and language.++Markets can also be used as a rule condition in Price Lists, making it easy to apply+region-specific pricing without duplicating products.++<Note>Before you can set up a Market for a country, you need to make sure that country is included in a configured Zone. See [<u>Zones</u>](https://spreecommerce.org/docs/user/settings/zones) for setup instructions.</Note>++To manage markets, navigate to **Settings → Markets** in the admin dashboard.++++## Markets Overview++The Markets table displays all configured markets with the following details:++- **Name** — the internal label for the market (e.g., "United States", "Europe")+- **Currency** — the currency customers in this market will see at checkout+- **Default Locale** — the primary language for this market+- **Default** — indicates which market is set as the default for new visitors++## Create a Market++To create a new market, click **New Market** in the top-right corner.++++Fill in the following fields:++- **Name** — an internal label to identify this market (e.g., "United Kingdom", "DACH Region")+- **Default Country** — the primary country for this market, used to determine default shipping+ and tax behaviour+- **Currency** — the currency displayed to customers in this market at checkout+- **Default Locale** — the primary language shown to customers in this market+- **Supported Locales** — additional languages customers can switch to within this market+- **Tax Inclusive** — check this if prices should be displayed with tax already included+ (common in VAT-inclusive markets such as the EU)+- **Default** — check this to make this the default market for visitors who haven't selected one++Once you've filled in the details, click **Create** to save the new market.++<Note>A country must be included in a configured Zone before it can be set as the Default Country for a Market. See Zones for setup instructions.</Note>++## Edit a Market++To edit a market, click on its row in the Markets table to open the edit form.++++The edit form contains the same fields as the creation form. Update the relevant fields and+click **Update** to save your changes.++## Delete a Market++To delete a market, click on its row to open the edit form, then click **Delete** at the+bottom of the page.++<Warning>Deleting a market cannot be undone. Before deleting, check that no active Price List rules or storefront configurations reference this market.</Warning>++## Related++- [<u>Zones</u>](https://spreecommerce.org/docs/user/settings/zones)+- [<u>Tax</u>](https://spreecommerce.org/docs/user/settings/tax)+- [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists)diff --git a/docs/v5/user/settings/metafields.mdx b/docs/v5/user/settings/metafields.mdxnew file mode 100644index 0000000000..29e39b88d2--- /dev/null+++ b/docs/v5/user/settings/metafields.mdx@@ -0,0 +1,116 @@+---+title: "Metafield Definitions"+description: "Define and manage custom metafields in Spree to attach extra structured data to products, orders, and other store objects without code changes."+canonical: "https://spreecommerce.org/docs/user/settings/metafields"+---++Metafields in Spree allow you to attach custom data to nearly any object in your store - without needing to write a single line of code or modify the database.++From product materials to internal order notes, metafields give you the flexibility to store, manage, and display extra information that doesn't come out of the box. This reduces reliance on developer deployments, makes experimentation easier, and enables faster iteration directly from the admin dashboard.++## Creating a New Metafield++To create a metafield definition go to **Settings → Metafield Definitions**++++Here you’ll see a list of all existing metafield definitions in your store.++To add a new one, click **New Metafield Definition** in the top right corner.++++Fill out the form with the required details:++- **Name** - this is the display name for the field, shown in the dashboard and/or storefront+- **Namespace** - used to group metafields and avoid naming conflicts+ - We recommend using something like “custom” for internal or merchant-defined fields+ - Avoid using common Spree model names like product, order, or variant as these may conflict with existing integrations+- **Key** - the unique identifier for the field, combined with the namespace+ - e.g.: custom.material, custom.internal_note+- **Resource** - choose the object the metafield applies to (see full list below)+- **Type** - the format of data the field should accept (see examples below)+- **Display on** - choose whether this field appears in the Admin only, or Admin and Storefront.++### Supported Resources++++You can define metafields for nearly any data object in Spree:++- **Address** - e.g., delivery instructions+- **Asset** - e.g., alt text or copyright+- **Credit Card** - e.g., vault token+- **Customer Return** - e.g., return reason detail+- **Gift Card** - e.g., personal message+- **Image** - e.g., display priority or alt tag+- **Line Item** - e.g., engraving or personalization notes+- **Newsletter Subscriber** - e.g., subscription source+- **Option Type** - e.g., an extended description for color choices+- **Option Value** - e.g., color hex code+- **Order** - e.g., internal comment, PO number+- **Payment** - e.g., external transaction reference+- **Payment Method** - e.g., risk profile or processor ID+- **Payment Source** - e.g., metadata from payment gateway+- **Post** - e.g., featured tag+- **Post Category** - e.g., CTA label+- **Product** - e.g., material, sustainability rating, care instructions+- **Promotion** - e.g., campaign name+- **Refund** - e.g., refund reason detail+- **Shipment** - e.g., fragile/handling notes+- **Shipping Method** - e.g., carrier code+- **Stock Item** - e.g., e.g., warehouse bin location+- **Stock Transfer** - e.g., batch ID or receiving note+- **Store** - e.g., store tagline or branding metadata+- **Store Credit** - e.g., usage restrictions+- **Tax Rate** - e.g., compliance category+- **Taxon** - e.g., display badge (“New”, “Sustainable”)+- **Taxonomy** - e.g., navigation group metadata+- **Variant** - e.g., spec sheet URL, sizing details+- **User** - e.g., loyalty tier+- **Vendor** - e.g., vendor profile details++### Supported Data Types++++Each metafield must be assigned a **type**, which determines the format of the stored value. Choosing the right type helps keep data structured, valid, and useful across the storefront and admin.++- **Short Text** - for single-line strings, e.g., "Cotton" or "Blue"+- **Long Text** - multi-line content, e.g., care instructions+- **Rich Text** - text with formatting options, e.g., marketing blocks+- **Number** - any numeric value, e.g., 4.5 (rating), 12 (inches)+- **Boolean** - true/false flags, e.g., “Is this product fragile?” = true+- **JSON** - for structured data or multiple related attributes++## Adding Metafield Values++Once your metafield definition has been created, you can enter values in a few different ways:++### Individually in the Admin Dashboard++First, navigate to the relevant resource (e.g., Product, Order, Shipment).++++Click the **three-dot menu** in the top right corner and select **Metafields** from the dropdown.++++Enter the desired values in the form and click **Save** to finalized your changes.++++This works for any individual resource type and is perfect for adding or editing a few metafields manually.++### In Bulk (Products Only)++Product metafields can also be imported or updated in bulk by:++1. Adding columns to your CSV file using this format: metafield.namespace.key (e.g. metafield.custom.material)+2. Entering the desired values for each product row.+3. Importing the file when uploading a new product catalog++You can also update your existing catalog by exporting the product file, updating it as described above, and then reimporting it to apply metafield updates++This is ideal for large-scale changes across multiple products, especially when onboarding a large catalog.diff --git a/docs/v5/user/settings/payments.mdx b/docs/v5/user/settings/payments.mdxnew file mode 100644index 0000000000..fb6ffa34b0--- /dev/null+++ b/docs/v5/user/settings/payments.mdx@@ -0,0 +1,120 @@+---+title: "Payments"+description: "Learn how to view, add, edit, and remove payment methods in Spree."+canonical: "https://spreecommerce.org/docs/user/settings/payments"+---++Payments are a vital part of any e-commerce store. Spree offers a flexible and modular system for managing payment methods, supporting both out-of-the-box and third-party options.++<Warning>+ Not all payment methods are available by default - most require the installation of additional gems by a developer before they can be used in the admin interface.+</Warning>++To manage payments, navigate to the Payments tab of the Settings menu.++++## Payment Methods Overview++++Here you can see a list of enabled payment methods, and a list of available payment methods:++### Enabled Payment Methods++++Enabled methods are those that are configured and can be used by customers on checkout.++You can easily modify the display settings of enabled payment methods by changing the visibility and active status.++++### Available Payment Methods++++Available payment methods are those that have been installed, but have not been configured yet.++### Default Payment Methods++By default, the following payment methods are available in Spree:++- **Store Credits**: allow customers to pay using store credits issued by the admin, enabled by default+- **Offsite Payment**: labelled as "Check", not enabled by default++### Third-Party Payment Methods++Additional payment gateways (e.g., Stripe) can be made available by having your developers install the relevant gems. For example, Stripe gateway is free to use, but requires adding the [<u>spree_stripe</u>](https://github.com/spree/spree_stripe) gem to your store's codebase before it becomes available in the admin interface.++For more information about our native Stripe integration, see Integrations → Stripe Gateway.++Once a payment method has been installed, it appears in the Available Payment Methods list. From there, it can be added, configured, or removed as needed.++## Add a Payment Method++To add a payment method, click Add on the corresponding row in the Available Payment Methods list. This will direct you to the payment method creation form for that method.++++Depending on the payment method you’re adding, the sections displayed in the form may differ. The following example covers Stripe which has 2 distinct sections:++### Payment Provider Settings++++Simply enter the required credentials into their respective fields.++<Note>+ This section only applies to third-party payment methods.+</Note>++<Warning>+ Different payment providers may require different credentials to be entered.+</Warning>++### Display Settings++++Display settings can be configured for all payment methods whether default or third-party.++There are four fields to configure:++- **Name**: The name displayed on the storefront+- **Display**: Where the method is available for use+ - On both the admin panel & storefront+ - Only on storefront+ - Only on admin panel+- **Auto Capture**: Determines whether payment is captured automatically at the time of authorization. Use the app default or override it per method.+- **Status**: Toggle whether the payment method is available for use in orders. Inactive methods are hidden but not deleted.++### Create++Once you’ve entered all the required fields, click Create to add the payment method.++The method will now be listed in your store’s enabled payment methods and will be available to users on checkout (provided it is active and visible).++## Edit a Payment Method++To edit a payment method, click on the corresponding row in the enabled payment methods list. This will direct you to the edit form for that method.++++Feel free to update any of the display settings for the payment method, but be very cautious when editing payment provider settings.++<Warning>+ Swapping payment provider accounts on an active store can disrupt payment processing and lead to failed transactions or reporting inconsistencies. Ensure all pending payments are settled and test the new account thoroughly in a staging environment before applying changes in production.+</Warning>++## Delete a Payment Method++To remove a payment method, simply open the edit form as shown above and click Delete.++<Warning>+ Once a payment method is associated with an order, it cannot be deleted.+</Warning>++<Note>+ Deleting a payment method moves it from the enabled payment methods list back into the available payments list. It does not uninstall the associated gem. A developer would need to remove it from the codebase if complete deactivation is desired.+</Note>\ No newline at end of filediff --git a/docs/v5/user/settings/policies.mdx b/docs/v5/user/settings/policies.mdxnew file mode 100644index 0000000000..2fd2d64a1f--- /dev/null+++ b/docs/v5/user/settings/policies.mdx@@ -0,0 +1,59 @@+---+title: "Policies"+description: "Learn how to set up and manage store policies in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/settings/policies"+---++Your store policies are an essential part of your eCommerce setup, helping you establish trust, maintain compliance, and communicate clearly with your customers. Spree allows you to easily manage these pages from the Policies tab.++You can create as many custom policy pages as you need, with full control over their content and URL structure.++The following four standard policies are added to every store by default:++- Terms of Service+- Privacy Policy+- Returns Policy+- Shipping Policy++These can be customized, deleted, or supplemented with additional policies depending on your business needs.++## Create a New Policy++To create a new policy, navigate to **Settings → Policies** in your Spree dashboard.++++Click **New Policy** in the top-right corner to open the policy creation form.++++Simply enter data into the following fields:++- **Name** - displayed title on the storefront.+- **Slug** - URL identifier (e.g. /policies/custom-warranty).+- **Content** - enter your policy text using the rich text editor (supports formatting, links, media, etc.).++Then, click **Create** to save and publish your new policy.++Once published, the policy will be accessible from the storefront and can also be linked in your footer navigation or other relevant areas.++++## Edit an Existing Policy++To edit an existing policy, navigate to **Settings → Policies** and follow these steps:++1. Click on the policy you’d like to update.+2. Modify the name, slug, or content as needed.+3. Click **Update** to save your changes.++Your edits will be reflected immediately on the live storefront.++## Delete a Policy++To delete an existing policy, navigate to **Settings → Policies** and follow these steps:++1. Click on the policy you’d like to delete.+2. Click **Delete** at the bottom of the page and confirm.++<Warning>Deleted policies are permanently removed and will no longer be accessible to customers.</Warning>diff --git a/docs/v5/user/settings/returns-configuration.mdx b/docs/v5/user/settings/returns-configuration.mdxnew file mode 100644index 0000000000..e1b8cd8217--- /dev/null+++ b/docs/v5/user/settings/returns-configuration.mdx@@ -0,0 +1,128 @@+---+title: "Returns Configuration"+description: "Learn how to define return authorization reasons, refund reasons, and reimbursement types."+canonical: "https://spreecommerce.org/docs/user/settings/returns-configuration"+---++Returns management is a crucial part of ecommerce operations. It builds customer trust, streamlines support workflows, and helps maintain clarity around inventory and financial adjustments.++Not all eCommerce platforms offer built-in tools for managing returns, but fortunately Spree does - no extra plugins or custom development needed.++To get started with Returns, navigate to the Returns tab of the Settings menu.++++Here you’ll notice three subtabs for managing Return Authorization Reasons, Refund Reasons, and Reimbursement Types. Let’s look at each in detail:++## Return Authorization Reasons++++Return Merchandise Authorizations (RMAs) specify the reasons a customer provides when requesting to return an item. These reasons help categorize returns for internal reporting and customer service workflows.++RMAs only have two fields:++- **Name**: The visible reason for the return (e.g., Wrong size, No longer needed).+- **Status**: Toggle whether the reason is available for use in the returns flow. Inactive reasons are hidden but not deleted.++### Add New Return Authorization++To add a new return authorization reason, click ‘New RMA Reason’ in the top right corner and you’ll be redirected to the RMA reason creation form.++++Simply enter the name, set the status, and click Create to save the new RMA reason.++### Edit Return Authorization++To edit an RMA reason, simply click on the RMA’s row in the overview.++++The Edit form looks more or less identical to the Create form, but with pre-filled data, and Update buttons rather than Create buttons.++Simply update fields as needed and then click Update to save changes.++### Delete Return Authorization++To delete an RMA reason, simply open the Edit form as shown above and click Delete.++## Refund Reasons++++Refund Reasons are used internally to explain why a refund was issued. These help with tracking, reporting, and communication across teams.++Refund reasons also have two fields:++- **Name**: A label for the reason (e.g., Return processing, Order cancelled).+- **Status**: Toggle whether the reason is available for use in the returns flow. Inactive reasons are hidden but not deleted.++### Add New Refund Reason++To add a new refund reason, click ‘New Refund Reason’ in the top right corner and you’ll be redirected to the refund reason creation form.++++Simply enter the name, set the status, and click Create to save the new refund reason.++### Edit Refund Reason++To edit a refund reason, simply click on its row in the overview.++++The Edit form looks more or less identical to the Create form, but with pre-filled data, and Update buttons rather than Create buttons.++Simply update fields as needed and then click Update to save changes.++### Delete Refund Reason++To delete a refund reason, simply open the Edit form as shown above and click Delete.++## Reimbursement Types++++Reimbursement Types define how refunds are paid back to the customer. These options help determine whether a refund goes back to the original payment method, a store credit, or is handled through an exchange.++Reimbursement types have four fields:++- **Name**: The label for this type (e.g., Store credit, Exchange).+- **Type**: The method of reimbursement:+ - Credit+ - Original payment (e.g., debit card)+ - Exchange+ - Store credit+- **Status**: Toggle whether the reason is available for use in the returns flow. Inactive reasons are hidden but not deleted.+- **Mutable**: If set to Yes, the reimbursement type can be changed after it's assigned, otherwise it's locked it in.++### Add New Reimbursement Type++To add a reimbursement type, click ‘New Reimbursement Type’’ in the top right corner and you’ll be redirected to the reimbursement type creation form.++++Simply enter the name, set the status, and click Create to save the new reimbursement type.++### Edit Reimbursement Type++To edit a reimbursement type, simply click on its row in the overview.++++The Edit form looks more or less identical to the Create form, but with pre-filled data, and Update buttons rather than Create buttons.++Simply update fields as needed and then click Update to save changes.++### Delete Reimbursement Type++To delete a reimbursement type, simply open the Edit form as shown above and click **Delete**.++## Processing Returns++Now that you’ve defined all of your RMA reasons, refund reasons, and reimbursement types, you’ll be ready to process returns in the event that a customer requests them.++To learn how to process returns, please refer to [Returns → Returns Processing](https://spreecommerce.org/docs/user/returns/returns-processing).++diff --git a/docs/v5/user/settings/sales-channels.mdx b/docs/v5/user/settings/sales-channels.mdxnew file mode 100644index 0000000000..7a1ebc566e--- /dev/null+++ b/docs/v5/user/settings/sales-channels.mdx@@ -0,0 +1,113 @@+---+title: "Sales Channels"+description: "Create and manage sales channels in Spree to run multiple storefronts, B2B portals, POS, and mobile apps with per-channel catalogs and order attribution."+canonical: "https://spreecommerce.org/docs/user/settings/sales-channels"+---++import { Since } from '/snippets/since.mdx';++<Since version="5.5" />++Sales channels let you run multiple distinct storefronts or selling contexts from a single Spree instance — each with its own product catalog, order attribution, and routing behaviour. A channel might represent a public-facing online store, a wholesale portal, a mobile app, a point-of-sale terminal, or a seasonal microsite.++When an order comes in through a given channel, Spree tags it automatically so you can filter, report, and route fulfilment by channel. Products can be assigned to one or more channels, giving you precise control over what each audience sees.++Common use cases include:++- **Online store + POS** — keep retail and in-person orders separate for reporting and fulfilment+- **B2C + B2B wholesale portal** — show different catalogues and pricing to different audiences from one backend+- **Marketplace or affiliate channel** — attribute orders to the source channel for commission tracking+- **Mobile app** — route mobile orders separately and track conversion independently+- **Seasonal microsite** — run a limited-time catalogue without affecting your main storefront++<Note>Developers connect a storefront or integration to a specific channel by passing the `X-Spree-Channel` header with the channel's code in API requests. See the [Spree API docs](https://spreecommerce.org/docs/api-reference/storefront) for details.</Note>++To manage sales channels, navigate to **Settings → Sales Channels** in the admin dashboard.++## Sales Channels Overview++++The Sales Channels table displays all configured channels with the following details:++- **Name** — the internal label for the channel (e.g., "Online Store", "Wholesale Portal")+- **Code** — the unique identifier used in API requests to attribute orders to this channel+- **Default** — indicates which channel is used when no channel is specified in a request+- **Active** — whether the channel is currently enabled++## Create a Sales Channel++To create a new channel, click **New Sales Channel** in the top-right corner.++++Fill in the following fields:++- **Name** — an internal label to identify this channel (e.g., "iOS App", "EU Wholesale")+- **Code** — a short, unique identifier used in API requests (e.g., `ios-app`, `eu-wholesale`). This cannot be changed after creation.+- **Active** — uncheck to disable this channel without deleting it+- **Default** — check to make this the fallback channel for orders placed without a channel header+- **Order Routing Strategy** — controls how orders placed through this channel are allocated to stock locations for fulfilment. Select from:+ - **Inherit from store** — uses the same routing strategy as the default channel+ - **Rules (ordered)** — sets up a rules-based strategy; the specific rules can be configured via code+ - **Legacy** — uses the original Spree fulfilment flow++Once you've filled in the details, click **Create** to save the new channel.++### Order Routing Strategy++Order routing determines which stock location fulfils an order when you have multiple warehouses or fulfilment points. When an order is placed, Spree evaluates the assigned strategy for that channel to decide where to source each shipment from.++Channels that serve different regions or customer types often benefit from dedicated routing rules — for example, routing wholesale orders to a separate warehouse, or ensuring a specific fulfilment centre handles all orders from a particular storefront.++When using the **Rules (ordered)** strategy, the following rules can be configured and arranged in priority order:++1. **Preferred location** — always attempts to fulfil from a specific, designated stock location first, regardless of stock levels at other locations+2. **Minimize stock locations** — tries to fulfil the entire order from as few stock locations as possible, reducing split shipments and simplifying fulfilment+3. **Default location** — falls back to a designated stock location when no other rule has been satisfied++<Note>Rule rankings within the Rules (ordered) strategy can be adjusted by a developer per channel. See the [<u>developer documentation</u>](https://spreecommerce.org/docs/developer/core-concepts/channels) for details.</Note>++## Products and Sales Channels++When a product is created, it is automatically assigned to the default channel only. Any additional channels must be assigned manually. This means products are not visible on non-default channels until explicitly added.++To manage which channels a product is available on, open the product in the editor and locate the **Publishing** card.++++Click **Manage** to add or remove the channels this product is assigned to.++++Once a channel is assigned, you can click on it in the Publishing card to configure its scheduling settings — including the start and end dates for when the product should be active on that channel.++++A product's availability per channel follows its publishing status:++- **Live** — visible and purchasable on that channel+- **Scheduled** — will become active automatically at the configured start date+- **Not available** — assigned to the channel but hidden from customers++This allows you to curate entirely different catalogues for different audiences — for example, showing a reduced range on a wholesale channel while keeping the full catalogue on the main storefront.++<Note>If creating products via the Admin API, the product will have no channels assigned unless a channel is explicitly set in the request.</Note>++## Orders and Sales Channels++Every order placed through a channel is automatically attributed to it, making it easy to track volume and manage fulfilment per channel without any manual tagging.++In the **Orders** list, a **Channel** column shows which channel each order came from at a glance. You can also use the **Channel** filter to narrow the list to a specific channel.++++Opening an individual order shows the channel attribution in the order summary panel at the bottom of the page.++++## Related++- [Spree Storefront API docs](https://spreecommerce.org/docs/api-reference/storefront)+- [<u>Markets</u>](https://spreecommerce.org/docs/user/settings/markets)+- [<u>Price Lists</u>](https://spreecommerce.org/docs/user/manage-products/price-lists)diff --git a/docs/v5/user/settings/shipping-methods.mdx b/docs/v5/user/settings/shipping-methods.mdxnew file mode 100644index 0000000000..cc1687875a--- /dev/null+++ b/docs/v5/user/settings/shipping-methods.mdx@@ -0,0 +1,106 @@+---+title: "Shipping Methods"+description: "Learn how to set up shipping methods in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/settings/shipping-methods"+---++If you want to run a successful online business, having shipping methods in place is essential. These methods appear at checkout, representing the carriers and services used to deliver your products to customers.++<Warning>If you don’t set up at least one shipping method for each region you sell to, customers in those regions won’t be able to complete their checkout.</Warning>++To set up shipping methods, navigate to **Settings → Shipping** in the Spree dashboard.++++## Add a New Shipping Method++To add a new shipping method, click **New Shipping Method** in the top right corner. This will open the shipping method creation form.++++This page is divided into seven distinct sections, so let’s take a look at each individually:++### Presentation++++Here you can set a descriptive name for the shipping method (e.g., UPS Standard, FedEx Next Day), and choose where it should be displayed.++<Warning>Make sure the **Display on** setting includes **storefront** if you want customers to see this shipping method on the checkout.</Warning>++### Tracking URL++++Here you can add the tracking URL format for the shipping carrier that’s associated with the payment method, e.g.:++- [<u>https://www.fedex.com/wtrk/track/?trknbr=:tracking</u>](https://www.fedex.com/wtrk/track/?trknbr=:tracking)+- [<u>https://www.ups.com/track?loc=en_US&tracknum=:tracking</u>](https://www.ups.com/track?loc=en_US&tracknum=:tracking)+- [<u>https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=:tracking</u>](https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=:tracking)++This way, you can simply enter the tracking number when fulfilling an order that’s using the associated shipping method, and the customer will receive the correct tracking link for their order.++<Warning>Make sure to verify the tracking link format for each shipping carrier you plan on using and test them before going live.</Warning>++### Zones++++Not all shipping methods should be available in every region - especially if you serve customers across multiple countries or continents. Zones allow you to define regional availability for each shipping method.++Simply select the appropriate Zone(s) to ensure the method only appears for customers in those regions. This helps you prevent invalid shipping options and tailor your delivery strategy to each market.++<Note>Customers will only see shipping methods that apply to their delivery address based on the assigned Zones.</Note>++### Shipping Categories++++Shipping Categories are especially useful when your store includes products with very different delivery needs. For example:++- Assigning a “Digital” category to non-physical products ensures they skip the shipping step during checkout.+- Creating a “Heavy” category for large or heavy items allows you to limit specific shipping methods to those products.++### Tax Category++++Use this setting to assign a Tax Category to the shipping method. This determines how taxes are applied to shipping charges at checkout.++Different types of products may be subject to different tax rules, and assigning a tax category here ensures that shipping is taxed appropriately based on the contents of the order.++For example:++- In some regions, digital goods may be exempt from shipping tax, while physical goods are not.+- Shipping charges related to tax-exempt products might also need to be excluded from tax calculations entirely.++Assigning the correct tax category helps you stay compliant with local tax regulations and ensures customers are charged accurately.++### Calculator++++This section determines how the shipping cost will be calculated for this method. Spree offers several calculator types to support different pricing strategies:++- **Flat Percent** - charges a percentage of the order total as the shipping cost.+- **Flat Rate** - charges a fixed shipping amount, regardless of order size or value.+- **Flexible Rate per package item** - charges a base rate plus an additional amount for each item in the package (ideal for variable-size orders).+- **Flat Rate per package item** - Applies the same fixed fee to every item in the shipment.+- **Price Sack** - offers tiered pricing based on the total order value (e.g., \$5 for orders under \$50, free over \$100).+- **Digital Delivery** - used for digital products that don’t require physical shipping (typically results in no shipping cost).++Each calculator type may reveal different fields depending on its configuration. Choose the one that best aligns with your fulfillment strategy.++For a more detailed guide on shipping calculators, please refer to another support article.++### Estimated Transit Business Days++++This optional setting allows you to display an estimated delivery time for the shipping method, visible on both the product detail page (PDP) and during checkout.++While not required, showing delivery estimates can help build trust, reduce cart abandonment, and improve conversions by setting clear expectations about when customers will receive their orders.++### Create Shipping Method++Once you’ve configured all of the above settings, simply click **Create** at the bottom of the page to save your new shipping method. It will become immediately available to customers provided the order details match the method’s configuration.diff --git a/docs/v5/user/settings/store-details.mdx b/docs/v5/user/settings/store-details.mdxnew file mode 100644index 0000000000..a43d5c501f--- /dev/null+++ b/docs/v5/user/settings/store-details.mdx@@ -0,0 +1,67 @@+---+title: "Store Details"+description: "Learn how to configure your store's core settings in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/settings/store-details"+---++The Store Details section is where you define your store's identity and core operational+preferences — from its name and logo to timezones, units of measurement, and how digital+downloads are handled.++To configure these settings, navigate to **Settings → Store Details** in the admin dashboard.++## Name & Logo++++- **Name** — the public-facing name of your store, displayed in headers, footers, and other+ storefront areas.+- **Logo** — upload a store logo (recommended size: 240x240 px). This image is used only in+ the admin dashboard.++## Currencies & Countries++<Note>Currency, locale, and regional settings are now managed in **Settings → Markets**. See [<u>Markets</u>](https://spreecommerce.org/docs/user/settings/markets) for full details.</Note>++## Standards & Formats++++Here you can set the timezone, unit system, and weight units to match your region and business+preferences:++- **Timezone** — set your store's timezone for accurate timestamps and order data.+- **Unit system** — choose between imperial and metric. This affects how weights and measures+ are displayed across your storefront:+ - Imperial system+ - Metric system+- **Weight unit** — choose the default unit for product weights:+ - Pound (lb) — imperial system+ - Ounce (oz) — imperial system+ - Kilogram (kg) — metric system+ - Gram (g) — metric system++## Phone & Address++++Enter your store's contact details here:++- **Phone** — your store's contact phone number.+- **Address** — your business address.++## Digital Assets++++Here you can control how digital products (e.g., downloads) are handled after purchase:++- **Limit digital links download days** — set how long download links remain active after+ purchase (in days).+- **Limit digital links download count** — restrict the number of times a download link can+ be used per purchase.++## Saving Changes++After making any updates, click **Update** at the bottom of the page to save your store+settings, otherwise any changes you've made will not be saved.diff --git a/docs/v5/user/settings/tax.mdx b/docs/v5/user/settings/tax.mdxnew file mode 100644index 0000000000..d883c838e5--- /dev/null+++ b/docs/v5/user/settings/tax.mdx@@ -0,0 +1,140 @@+---+title: "Tax"+description: "Learn how to configure tax rates and categories for your Spree store."+canonical: "https://spreecommerce.org/docs/user/settings/tax"+---++Tax management is critical in eCommerce to ensure legal compliance, avoid costly penalties, and provide accurate pricing for customers across different regions.++Spree gives you a clear and customizable way to set up and manage taxes for any region, product type, or pricing style, whether you include tax in your prices (like VAT) or apply it at checkout (like U.S. sales tax).++To manage tax configurations, navigate to **Settings → Tax** in the admin dashboard.++++You'll see two subtabs here — **Tax Rates** and **Tax Categories** — for managing each.++++Let's look at each in more detail:++## Tax Rates++++The Tax Rates overview displays all existing tax rates with key information such as:++- **Name**: A label for storefront and internal display+- **Tax Category**: Which group of products this rate applies to+- **Zone**: Where the tax applies (configured separately in the Zones section)+- **Amount**: The tax percentage (e.g., 20%)+- **Included in Price**: Whether this tax is part of the listed price+- **Show Rate in Label**: Whether this tax rate appears as part of the price label on the storefront++From here, you can add new tax rates or edit existing ones.++<Note>Tax rates in Spree rely on the Zones feature to determine where each rate applies. Zones define geographic regions (like countries or states), allowing you to target specific tax rules based on a customer's shipping address. See [<u>Settings → Zones</u>](/v5/user/settings/zones) for more.</Note>++### Add a New Tax Rate++To add a new tax rate, click **New Tax Rate** in the top-right corner. You'll be taken to the tax rate creation form.++++Fill in the form with the relevant information:++- **Name** — A label for this tax rate, shown internally and, if enabled, on the storefront.+- **Zone** — The geographic region this rate applies to, selected from your existing zones.+- **Tax Category** — The group of products this rate applies to, selected from your existing tax categories.+- **Calculator** — Determines how tax is calculated for this rate — see Calculators below.+- **Amount** — The tax rate as a decimal (e.g., enter `0.05` for 5%).+- **Included in Price** — Whether this tax is already built into the listed price (Yes) or added at checkout (No).+- **Show Rate in Label** — Whether this rate's percentage appears alongside the price on the storefront.++Once the data has been entered, click **Create** to save the new tax rate.++This tax rate can now be applied to products with the matching category and shipping to the selected zone.++#### Calculators++Spree offers three calculators for determining how tax is calculated on a tax rate:++- **Default Tax Calculator** — A simple calculator that applies the tax rate's **Amount** directly to any product assigned to the associated tax category.+- **Stripe Tax Calculator** — Automatically calculates tax at checkout based on the customer's shipping address. Only works if you're using Stripe as your payment gateway, and requires tax nexus to be set up in your Stripe dashboard. See the [<u>Stripe integration guide</u>](/integrations/payments/stripe) for setup details.+- **AvaTax Transaction Calculator** — Automatically calculates tax at checkout based on the customer's shipping address. Requires an Avalara account, with the AvaTax integration installed and configured in Spree. See the [<u>Avalara AvaTax integration guide</u>](/integrations/tax/avalara) for setup details.++<Note>If you're using the AvaTax Transaction Calculator, you don't need to manually create tax rates here — it's enough to set up your tax categories and assign them to products. Spree creates the matching tax rates automatically as orders are placed.</Note>++### Edit a Tax Rate++To edit a tax rate, click its row in the Tax Rates overview.++++The edit form looks the same as the New Tax Rate form, but pre-filled with the existing data, and with an **Update** button instead of **Create**.++Update the fields as needed, then click **Update** to save your changes.++<Note>Changing a tax rate will affect all future orders using that rate, but not past orders.</Note>++### Delete a Tax Rate++To delete a tax rate, open its edit form and click **Delete** in the lower-right corner.++## Tax Categories++++Tax categories organize your products based on how they're taxed.++For example, if you sell both clothing and electronics, you might create a **Clothing** category taxed at a reduced or exempt rate (common in regions where apparel gets special tax treatment) and a **Standard** category for electronics taxed at the full rate — each product is then assigned to whichever category matches how it should be taxed.++<Note>A product variant can only be assigned one tax category at a time.</Note>++The Tax Categories overview displays all existing tax categories with key information such as:++- **Name**: e.g., Standard, Reduced, Exempt+- **Tax Code**: Optional code for integrations or accounting+- **Description**: Internal notes on what this category covers+- **Default**: Whether this is the default category for new products++From here, you can add new tax categories or edit existing ones.++### Add a New Tax Category++To add a new tax category, click **New Tax Category** in the top-right corner. You'll be taken to the tax category creation form.++++Fill in the form with the relevant information:++- **Name** — A label for this tax category, e.g., Standard, Reduced, or Exempt.+- **Tax Code** — An optional code used by integrations or your accounting system to classify this category.+- **Description** — Optional internal notes on what this category covers.+- **Default** — Whether new products should automatically be assigned this tax category.++Once the data has been entered, click **Create** to save the new tax category.++This category will now be available for assignment to products and tax rates.++### Edit a Tax Category++To edit a tax category, click its row in the Tax Categories overview, update the fields as needed, then click **Update** to save your changes.++<Note>You can switch the default tax category if needed, but only one can be default at a time.</Note>++### Delete a Tax Category++To delete a tax category, open its edit form and click **Delete** in the lower-right corner.++## Other Tax Integrations++In addition to the Stripe Tax and AvaTax calculators covered above, Spree's tax system is extensible — developers can build custom calculators to connect with other tax services (such as TaxJar) or implement custom tax logic specific to your business.++Get in touch with us if you'd like help implementing a custom tax integration.++## Related++- [<u>Settings → Zones</u>](/v5/user/settings/zones)+- [<u>Stripe integration guide</u>](/integrations/payments/stripe)+- [<u>Avalara AvaTax integration guide</u>](/integrations/tax/avalara)diff --git a/docs/v5/user/settings/users.mdx b/docs/v5/user/settings/users.mdxnew file mode 100644index 0000000000..05838b6ee3--- /dev/null+++ b/docs/v5/user/settings/users.mdx@@ -0,0 +1,82 @@+---+title: "Users"+description: "Invite, edit, and manage admin users in the Spree dashboard — send invitations, assign roles, track pending invites, and control backend access for your team."+canonical: "https://spreecommerce.org/docs/user/settings/users"+---++Effectively managing user access to your store’s backend is essential for operational security and team collaboration. The Users settings section allows you to view active users, track invitations, and (eventually) create roles to define permissions.++To manage admin users, navigate to the Users tab of the admin dashboard.++++This page is split into three subsections for Users, Invitations, and Roles. Let’s take a look at each in detail:++## Users++++This section displays a list of all active users with access to the dashboard. From here, you can invite new users, view existing user details, and remove access if needed.++### Invite a User++To invite a new user, click ‘Send Invitation’ in the top right corner.++++Then follow these steps:++1. Enter the users email address+2. Set their user role+3. Set an invitation expiry date+4. Click ‘Send Invitation’++The user will then receive an email invitation to the specified email address.++When they click on the invitation link, they’ll be redirected to an account creation page.++++Once they complete the form and click ‘Create a new account’ they’ll be redirected to the admin dashboard.++### Edit a User++To edit a user, click on their corresponding row to open their admin profile.++++Click Edit in the details section to reveal the edit form.++++Change the fields as needed and click Update to save.++### Delete a User++It’s not possible to outright delete a user, but you can block their access by removing their role in the edit form shown above.++## Invitations++++This section shows a record of all invitations that have been sent, whether accepted, pending, or expired. This helps you monitor who’s been invited, by whom, and what role they’ve been assigned.++Each invitation includes:++- **Email**: The email address the invitation was sent to+- **Inviter**: The user who sent the invitation+- **Role**: The assigned role upon acceptance+- **Created at**: Date the invitation was created+- **Status**: Accepted, Pending, or Expired++<Note>+ Pending invitations can be Resent or Deleted by clicking on the three dots on the right hand side of the corresponding row and selecting the desired action.+</Note>++## Roles++++Role-based access control is not yet fully implemented in the admin UI. While you can create new role names, they do not affect permission levels.++However, you can currently create roles and apply permissions to them via code. Please refer to our developer docs for more info: [<u>Customization → Permissions</u>](/v5/developer/customization/permissions).diff --git a/docs/v5/user/settings/zones.mdx b/docs/v5/user/settings/zones.mdxnew file mode 100644index 0000000000..8fb6da804a--- /dev/null+++ b/docs/v5/user/settings/zones.mdx@@ -0,0 +1,105 @@+---+title: "Zones"+description: "In this Spree user doc, you’ll learn how to create, edit and delete zones."+canonical: "https://spreecommerce.org/docs/user/settings/zones"+---++Zones allow you to define and group geographical areas (either by country or state) for greater control over how your store handles tax, shipping, and market settings. They allow you to carefully tailor your operations to specific regions.++To manage Zones, navigate to the Zones tab in the Settings menu.++## Zones Overview++++The Zones overview displays all existing zones with key details like:++- Name (e.g., “Asia”, “US States”, etc.)+- Description (e.g., Countries that make up the EU VAT zone)+- Default Tax Zone (Yes/No)++From here you can:++- Add a new zone+- Edit existing zones++## Add a New Zone++To add a new zone, click ‘New Zone’ in the top right corner, and you’ll be directed to a zone creation form.++++Here you’ll see two sections that allow you to define the new zone:++### General Settings++++Here you can set:++- **Name**: Internal name of the zone (e.g., "US States", "Europe", "Asia")+- **Description**: Optional, used for internal clarification+- **Default Tax Zone**: Toggle if this should be the fallback zone for tax rules+- **Type**: Choose between Country-based or State-based++### Location Selection++This section differs based on the chosen Type:++#### Country-Based++++If you choose the Country-based zone type, you’ll be presented with a multi-select list of countries. Select from options like:++- United States+- Japan+- Poland+- etc.++#### State-Based++++If you choose the State-based zone type, you’ll first be asked to choose a country (e.g., United States). Then, you can select individual states from that country.++For example, if you choose the U.S., the options would include:++- California+- Texas+- New York+- Armed Forces (Africa, Americas, Pacific)+- etc.++<Note>+ You can add multiple states or countries to each zone depending on your needs.+</Note>++## Edit a Zone++To edit a zone, simply click on the zone’s row in the Zones overview.++++The edit form looks more or less identical to the New Zone form, but with pre-filled data, and Update buttons rather than Create buttons.++Here you can:++- Update the name and description+- Change the type (Warning: switching types will reset the current selections, this is irreversible)+- Add/remove Countries or States+- Toggle default tax zone as needed++## Delete a Zone++To delete a zone, simply navigate to the editor for the zone you wish to delete, and click the ‘Delete’ button on the lower righthand side.++## Saving Changes++After making any updates (besides after deleting a zone), make sure to click Create or Update at the bottom of the page to save your zone settings, otherwise any changes you’ve made will not be saved.++## Pro Tips++- Use state-based zones when you need tax/shipping rules for specific U.S. states.+- Use country-based zones for international markets or VAT jurisdictions.+- Only one zone can be the Default Tax Zone.\ No newline at end of filediff --git a/docs/v5/user/user-quickstart-guide.mdx b/docs/v5/user/user-quickstart-guide.mdxnew file mode 100644index 0000000000..ac52e4095a--- /dev/null+++ b/docs/v5/user/user-quickstart-guide.mdx@@ -0,0 +1,123 @@+---+title: "User Quickstart"+description: "Launch a Spree Commerce store fast: configure payments and taxes, add products, set a support email, and complete the Getting Started onboarding checklist."+canonical: "https://spreecommerce.org/docs/user/user-quickstart-guide"+---++Spree Commerce gives you a powerful, flexible platform to build and manage your online store - but before you can start selling, there are a few key steps to complete.++This guide walks you through the essential setup tasks, from configuring payments and taxes to adding products and launching your storefront. Whether you're launching an MVP or just exploring Spree’s capabilities, this guide will help you get up and running quickly.++## Getting Started++++When you log into a fresh Spree Commerce instance, you’ll land on the Getting Started tab - a quick-launch checklist that helps you configure the essentials and go live faster.++You’ll see four key onboarding tasks:++- Setup payments+- Add products+- Set customer support email+- Setup taxes collection++Once all tasks are completed, the checklist will disappear from view. Let’s walk through each step below.++### Setup Payment Method++++To sell anything, you’ll need to configure at least one payment method.++Click **Setup Payment Method** to jump to **Settings → Payments**.++++At the top, you’ll see your currently enabled methods (e.g., Store Credits, added by default).++Below that is a list of available payment methods you can add, such as Stripe, Adyen or PayPal.++<Note>Only payment methods that have been installed will appear in the Available Payment Methods list. If a method you’re expecting isn’t listed, ask your developer to confirm it has been added to the codebase.</Note>++To add a method:++1. Click **Add** next to your chosen method+2. Follow the setup instructions in the form+3. Click **Create** to enable it++<Note>Most payment gateways require you to have an account with the provider before setup.</Note>++To learn more about available methods and configuration, see [<u>Payments</u>](https://spreecommerce.org/docs/user/settings/payments).++### Add Products++++There are three ways to populate your store’s catalog:++- [<u>Add products manually</u>](https://spreecommerce.org/docs/user/products/creating-products) (ideal for small catalogs or testing)+- Import products using CSV (essential for large catalogs)+- [<u>Invite vendors to add their own products</u>](https://spreecommerce.org/docs/user/vendors/invite-vendor) (for marketplaces - Spree Enterprise only)++Click the **Add Products** button to start adding manually, or refer to the relevant articles based on your method.++Once you’ve added some products, make sure to set them as **Active** to publish them on the storefront.++For more detailed guides on creating and managing products, see:++- [<u>Creating Products</u>](https://spreecommerce.org/docs/user/products/creating-products)+- [<u>Editing Products</u>](https://spreecommerce.org/docs/user/products/editing-products)+- [<u>Editing Multi-Variant Products</u>](https://spreecommerce.org/docs/user/products/editing-multi-variant-products)+- [<u>Managing Products in Bulk</u>](https://spreecommerce.org/docs/user/manage-products/bulk-product-operations)++### Add Customer Support Email++++This small but critical step ensures customers know how to reach you.++Simply enter your customer support email in the field provided, and click **Save**.++This address will appear on your storefront and works as a contact for your customers in case they have any queries or require support.++### Setup Taxes Collection++++To charge the correct taxes at checkout, click **Setup Tax Rates** to be taken to **Settings → Tax**.++From here, you can configure:++- Tax rates (manual or through third-party services like Avalara)+- Tax categories++For full instructions, please refer to our [<u>Tax support article</u>](https://spreecommerce.org/docs/user/settings/tax).++## Shipping Methods++++Customers won’t be able to complete orders without at least one shipping method configured.++To configure a shipping methods, go to **Settings → Shipping** and click **New Shipping Method** to define:++- Shipping zones+- Cost calculator settings+- Estimated delivery times+- Shipping and Tax categories+- Tracking links++See [<u>Shipping Methods</u>](https://spreecommerce.org/docs/user/settings/shipping-methods) for a full breakdown of settings and examples.++<Note>By default, all Spree stores have a Digital Delivery method pre-configured. If you plan on selling digital products, be sure to assign those products the Digital shipping category.</Note>++## Next Steps++Once you’ve completed the basic setup, you’re ready to explore more advanced features and tailor your store to your business model. Here’s some recommended reading:++- [**<u>Learn how to manage orders</u>**](https://spreecommerce.org/docs/user/orders/processing-orders) - process payments, fulfill shipments, create and edit orders+- [**<u>Learn how to process returns</u>**](https://spreecommerce.org/docs/user/returns/returns-processing) - configure returns flow, authorize returns, reimburse customers+- [**<u>Launch a B2B storefront</u>**](https://spreecommerce.org/docs/use-case/b2b/b2b-commerce-model) - offer net terms, tiered pricing, company accounts, and purchase flows optimized for wholesale+- [**<u>Build a multi-vendor marketplace</u>**](https://spreecommerce.org/docs/use-case/marketplace/model) - invite third-party vendors to sell through your platform+- [**<u>Create a multi-tenant platform</u>**](https://spreecommerce.org/docs/use-case/multi-tenant/multi-tenant-model) power multiple stores or clients from a single backend+- [**<u>Sell digital products</u>**](https://spreecommerce.org/docs/use-case/digital-products/model) - deliver files automatically, skip shipping steps, and disable inventory trackingdiff --git a/docs/v5/user/using-spree.mdx b/docs/v5/user/using-spree.mdxnew file mode 100644index 0000000000..6de6b5aaed--- /dev/null+++ b/docs/v5/user/using-spree.mdx@@ -0,0 +1,55 @@+---+title: "Using Spree Commerce"+description: "How do I start using Spree for my project? Should I pick the free open-source Community Edition? What is the pricing for the Enterprise Edition?"+canonical: "https://spreecommerce.org/docs/user/using-spree"+---++First, you'd need to decide which Spree edition is a good fit for your project:++<CardGroup cols={2}>+ <Card title="Community Edition" href="https://github.com/spree/spree/">+ Spree Community Edition is free. It's the DIY version of Spree. It comes with community support only.+ </Card>++ <Card title="Enterprise Edition" href="https://spreecommerce.org/enterprise/">+ Spree Enterprise Edition comes with more features, more security, more integrations and enterprise support.+ </Card>+</CardGroup>++So what sets both versions apart? Here's a [feature comparison](https://spreecommerce.org/enterprise/) of the two editions and here's an [in-depth overview](https://spreecommerce.org/spree-commerce-version-comparison-community-edition-vs-enterprise-edition/).++To start using Spree, either version, the steps are usually:++<Steps>+ <Step title="Setup">+ Set up your Spree application (backend and storefront)+ </Step>++ <Step title="Customize">+ Customize Spree to meet your business needs+ </Step>++ <Step title="Go live!">+ Deploy to your preferred hosting/cloud provider+ </Step>+</Steps>++<Tip>Not a developer yourself? Talk to us about [hiring a team for your project](https://spreecommerce.org/get-started/).</Tip>++## Looking for Developer Documentation?++This Spree user documentation is intended for business owners and site administrators of Spree e-commerce sites. Everything you need to know to configure and manage your Spree store can be found here.++If you are a developer, you may find the [Developer Guides](/docs/developer) to be of benefit to you, though we strongly urge you to read through both sets of guides.++BTW Give Spree a [GitHub Star](https://github.com/spree/spree)<Icon icon="star" iconType="solid" color="#FFD43B" />, why don't ya?++Thank you for supporting Spree open-source! <Icon icon="heart" iconType="solid" color="#FF0000" />++## Join Spree Discord++To join the Spree Community and over 6000+ Spree users and developers, please join our [Discord](https://discord.spreecommerce.org/)++## Contact us++If you'd like to get in touch to share your feedback, request features, or start a new project, please fill out this contact form: [https://spreecommerce.org/get-started/](https://spreecommerce.org/get-started/)diff --git a/docs/v5/user/vendors/commission-rates.mdx b/docs/v5/user/vendors/commission-rates.mdxnew file mode 100644index 0000000000..4ac27827ba--- /dev/null+++ b/docs/v5/user/vendors/commission-rates.mdx@@ -0,0 +1,71 @@+---+title: "Commission Rates"+description: "Learn how to set and override commission rates across your multi-vendor marketplace in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/vendors/commission-rates"+---++<Warning>Multi-vendor capabilities are only available in Spree Enterprise Edition.</Warning>++Your commission rate is the percentage of each sale that your marketplace retains from a vendor's revenue — it's how the marketplace itself makes money, so getting it right matters. But "right" rarely means a single rate that fits every vendor and every product, which is why Spree lets you set commission rates at three different levels.++You can start with a single default rate for the whole marketplace, override it for specific vendors when you bring them on, and then fine-tune it even further at the individual product level. The most specific rule always wins, so you can layer overrides confidently without worrying about conflicts.++## 1. Default Marketplace Commission Rate++The default rate is the baseline that applies to every newly invited vendor unless overridden. It's configured under **Settings → Marketplace** and is the rate every other level falls back on.++See [<u>Marketplace Configuration</u>](https://spreecommerce.org/docs/user/settings/marketplace) for details on setting and updating the default.++<Note>Changing the default rate only applies to vendors invited after the change — existing vendors keep their current rate. To update an existing vendor, use one of the vendor-specific methods below.</Note>++## 2. Vendor-Specific Commission Rate++You can set a custom commission rate for individual vendors in two ways: during the invitation flow, or from the vendor's profile after they've been invited.++### When Inviting a Vendor++For WooCommerce and Manual/CSV vendors, the Invite Vendor form includes a **Commission Rate** field where you can set the rate at the same time you send the invitation. This is the easiest way to onboard a vendor on a custom rate from day one.++See [<u>WooCommerce Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-woocommerce) or [<u>Manual/CSV Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-manual) for the full invitation flow.++<Note>Shopify vendors don't go through the email invitation flow, so commission rates for Shopify vendors are set from the vendor profile after they've signed up. See the next section.</Note>++### From the Vendor Profile++For existing vendors (and for Shopify vendors), you can update the commission rate at any time from their vendor profile.++Navigate to **Vendors** in the admin dashboard and click on the vendor you'd like to update.++++Find the **Commission Rate** field on the vendor profile page and update it to the new percentage.++++Click **Update** at the bottom of the page to save your changes.++## 3. Product-Specific Commission Rate++For the most granular control, you can override the commission rate on individual products — useful when a vendor's catalog includes items with very different margins, or when you've struck a deal on a specific product with a vendor.++Navigate to **Products** in the admin dashboard and open the product you'd like to update.++++Scroll down to the **Platform Fee** section of the product editor and update the commission rate.++++Click **Update** at the bottom of the page to save your changes.++<Note>A product-specific commission rate overrides both the vendor-specific rate and the marketplace default for that product.</Note>++## Which Rate Applies?++When a sale is processed, Spree applies the most specific commission rate available, in the following order:++1. **Product-specific rate** — if set on the product, this wins.+2. **Vendor-specific rate** — if no product rate is set, the vendor's rate is used.+3. **Marketplace default rate** — if neither of the above is set, the default applies.++This means you can keep your overrides minimal — only set them where you genuinely need to deviate from the rate above.diff --git a/docs/v5/user/vendors/multi-vendor-checkout.mdx b/docs/v5/user/vendors/multi-vendor-checkout.mdxnew file mode 100644index 0000000000..99e1fd81b4--- /dev/null+++ b/docs/v5/user/vendors/multi-vendor-checkout.mdx@@ -0,0 +1,57 @@+---+title: "Multi-Vendor Checkout"+description: "Learn how multi-vendor checkout works in Spree Commerce — customers shop across multiple vendors in a single cart and complete one unified checkout."+canonical: "https://spreecommerce.org/docs/user/vendors/multi-vendor-checkout"+---++<Warning>Multi-vendor capabilities are only available in Spree Enterprise Edition.</Warning>++One of the biggest UX challenges in running a multi-vendor marketplace is the cart and checkout flow. Many marketplaces force customers to check out separately for each vendor — adding friction, hurting conversion rates, and frustrating shoppers who just want to buy what's in their cart and move on. Spree Commerce solves this with native multi-vendor checkout: customers can fill a single cart with products from any number of vendors, pick the shipping method they want for each vendor's package, pay once, and receive separate tracking updates as each vendor fulfills their part of the order.++Best of all, there's nothing to configure. Multi-vendor checkout is supported out of the box with the Spree Next.js Storefront starter — as long as your marketplace is running on the multi-vendor module and the Next.js storefront, customers will get the full multi-vendor checkout experience automatically.++## How It Works++### Adding Items from Multiple Vendors++Customers shop across all vendor catalogs as one experience. Products from different vendors are added to a single shared cart — to the customer, it feels like shopping any normal online store.++++### Selecting Shipping Methods at Checkout++At checkout, customers are shown the shipping methods available for each vendor's package separately, grouped by vendor. They select one shipping method per vendor and continue without needing to leave the checkout flow.++++This is where Spree's multi-vendor checkout really shines: shoppers retain full control over how each shipment is fulfilled (express, standard, pickup, etc.) without juggling multiple separate checkouts.++### Completing Payment++The customer pays once for the full order, with all vendor totals consolidated into a single transaction. Behind the scenes, Spree records the order as a single customer purchase but prepares it to be split into separate suborders for downstream processing.++## What Happens After Checkout++Once the order is placed, Spree automatically splits it into suborders — one per vendor involved in the order. Each suborder is then routed to where the vendor will actually fulfill it:++- **Manual/CSV vendors** see their suborder in their Spree vendor dashboard.+- **Shopify vendors** see their suborder in their Shopify admin (in addition to their Spree vendor dashboard), thanks to the marketplace's Shopify sales channel app.+- **WooCommerce vendors** see their suborder in their WooCommerce admin (in addition to their Spree vendor dashboard), via the WooCommerce integration.++This means each vendor handles the part of the order that belongs to them in the environment they're most comfortable with — without ever needing to see or coordinate with other vendors involved in the same customer purchase.++## Fulfillment and Tracking++Each vendor ships their portion of the order independently — using their own carriers, packaging, and timelines. As each vendor marks their package as fulfilled in their dashboard, the customer receives a separate tracking email for that specific shipment.++A customer who ordered from three vendors will receive three independent tracking notifications as each package ships, with no risk of confusion between them. From the marketplace's perspective, all of this happens automatically — no manual coordination is required between vendors, the marketplace owner, or the customer.++## Next Steps++For more on how vendors fulfill orders from their own dashboards, see the relevant onboarding guide:++- [<u>Shopify Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-shopify)+- [<u>WooCommerce Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-woocommerce)+- [<u>Manual/CSV Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-manual)++For marketplace-wide configuration that affects checkout (including commission rates and payout schedules), see [<u>Marketplace Configuration</u>](https://spreecommerce.org/docs/user/settings/marketplace).diff --git a/docs/v5/user/vendors/vendor-management.mdx b/docs/v5/user/vendors/vendor-management.mdxnew file mode 100644index 0000000000..5602a96cad--- /dev/null+++ b/docs/v5/user/vendors/vendor-management.mdx@@ -0,0 +1,148 @@+---+title: "Vendor Management"+description: "Learn how to view, manage, and configure vendors from the admin dashboard in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/vendors/vendor-management"+---++<Warning>Multi-vendor capabilities are only available in Spree Enterprise Edition.</Warning>++Running a marketplace means juggling relationships with potentially dozens or hundreds of vendors — each at a different stage of onboarding, with their own product catalogs, revenue trajectories, and operational needs. The Vendors tab is mission control for all of it.++From a single page, you can see the status of every vendor, dig into any individual vendor's full profile to manage their branding, commission rate, payout schedule, and storefront policies, and review their products, orders, and team in detail. Whether you're approving a new vendor that just finished onboarding, troubleshooting one that's stuck, or pulling lifetime revenue figures for a top performer, this is where it all happens.++To get started, navigate to **Vendors** in the admin dashboard.++## Vendor List Overview++The main table displays every vendor on your marketplace alongside key metrics and status indicators.++++The default columns are:++- **Name** - the vendor's brand or company name.+- **Status** - the current state of the vendor relationship:+ - **Invited** - invitation sent, not yet accepted.+ - **Onboarding** - vendor is working through onboarding tasks.+ - **Ready for Review** - vendor has completed onboarding and is awaiting your approval.+ - **Approved** - vendor is live and selling on the marketplace.+ - **Rejected** - vendor was not approved during review.+ - **Suspended** - vendor's access has been temporarily revoked.+- **Onboarding Progress** - a count of completed onboarding tasks (e.g., 4/6).+- **Integration** - the vendor's connection type:+ - **Shopify**+ - **WooCommerce**+ - **N/A** (Manual/CSV vendors)+- **Products** - total number of products in the vendor's catalog.+- **Revenue** - lifetime sales generated by the vendor.+- **Commission** - lifetime commission your marketplace has earned from the vendor.+- **Created At** - when the vendor was first invited.++From this view you can apply filters, sort by any column, customize the visible columns, and export the data by clicking **Export** in the top right corner.++## Managing a Vendor++To manage a specific vendor, click their row in the table to open their full vendor profile.++++From the vendor profile you can view and configure the sections below.++### Branding++++Click **Edit** at the top of the profile to open the branding panel. You can configure:++- **About** - a short description of the vendor.+- **Logo** - the vendor's primary logo (rectangular formats supported).+- **Square Logo** - recommended for avatars and compact display areas.+- **Cover Photo** - a wider banner image, similar to a Facebook cover photo.++These assets may be displayed on the vendor's storefront pages and within their vendor dashboard.++### Onboarding Progress++++A detailed breakdown of which onboarding tasks the vendor has and hasn't completed.++This helps you:++- Identify blockers that are holding a vendor up.+- Follow up with vendors who are stuck mid-flow.+- Approve vendors once they've met all the requirements.++For a walkthrough of what vendors see during onboarding, see [<u>Shopify</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-shopify), [<u>WooCommerce</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-woocommerce), or [<u>Manual/CSV Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-manual).++### Account Information++++A quick snapshot of vendor performance and financial terms:++- **Commission Rate** - the rate currently applied to this vendor. Click the pencil icon to update.+- **Number of Products** - total products in the vendor's catalog.+- **Total Sales** - lifetime sales generated by the vendor.+- **Country / Location** - the vendor's registered country.++For more on how commission rates work across the marketplace, see [<u>Commission Rates</u>](https://spreecommerce.org/docs/user/vendors/commission-rates).++### Payments & Payouts++++If the vendor is using Stripe Connect, you can manage their payout setup here:++- **Stripe Account ID** - copy the vendor's Stripe Account ID for reference or support purposes.+- **Payout Schedule** - how often the vendor receives payouts. Options:+ - **Daily**+ - **Weekly**+ - **Bi-weekly**+ - **Monthly**+ - **Use Marketplace Default Interval**++<Warning>Stripe Connect is only available in Spree Enterprise Edition. If your marketplace uses a different payment provider, payout schedule controls won't be available here.</Warning>++For more on configuring payout schedules across the marketplace, see [<u>Vendor Payouts</u>](https://spreecommerce.org/docs/user/vendors/vendor-payouts).++### Returns & Billing Address++++These sections display the vendor's registered returns and billing addresses. Both are view-only — vendors update their own addresses from their vendor dashboard.++## Vendor Subtabs++Similar to customer profiles, the vendor profile includes several subtabs for deeper management of the vendor's activity.++++### Overview++A sales-over-time graph and a list of the vendor's top-performing products — useful for a quick performance read at any point.++### Products++Every product associated with the vendor. From here you can apply filters, sort results, perform bulk actions, and review product-level performance.++### Orders++Every order placed with the vendor. You can filter orders, review payment and shipment states, and monitor fulfillment activity.++### Users++All vendor users associated with the account — that is, users who have accepted invitations and now have access to the vendor dashboard. Useful for tracking who on the vendor's team has access.++### Invitations++All invitations sent to vendor users. From this tab you can see invitation status, copy pending invite links, and monitor which users haven't yet joined.++### Policies++The vendor's policies, including:++- **Returns Policy** (default)+- Any other policies you require from the vendor++Admins can edit these policies directly from this section.diff --git a/docs/v5/user/vendors/vendor-onboarding-manual.mdx b/docs/v5/user/vendors/vendor-onboarding-manual.mdxnew file mode 100644index 0000000000..77610ea2bb--- /dev/null+++ b/docs/v5/user/vendors/vendor-onboarding-manual.mdx@@ -0,0 +1,159 @@+---+title: "Manual/CSV Vendor Onboarding"+description: "Learn how to invite and onboard a vendor who'll upload products manually or via CSV to your multi-vendor marketplace in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/vendors/vendor-onboarding-manual"+---++<Warning>Multi-vendor capabilities are only available in Spree Enterprise Edition.</Warning>++<Note>This guide covers vendors who'll add products manually through the vendor dashboard or import them via CSV. For other vendor types, see [<u>Shopify Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-shopify) and [<u>WooCommerce Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-woocommerce).</Note>++Not every vendor will be running on Shopify or WooCommerce. Some don't yet have an online store at all, some use platforms without a direct Spree integration, and some simply prefer to manage their marketplace catalog independently. For all of these cases, the Manual/CSV onboarding path is the catch-all — it works with any vendor regardless of their backend setup.++Onboarding a Manual/CSV vendor has two distinct parts: an **Admin Setup** that the marketplace owner completes by sending an invitation, and a **Vendor Onboarding** flow that the vendor themselves completes after receiving the invite.++## Prerequisites++Before you can onboard Manual/CSV vendors, you'll need:++- The **`spree_multi_vendor` Enterprise gem** installed on your Spree instance.++---++## Admin Setup++This section is for the marketplace owner. Inviting a Manual/CSV vendor uses the same invitation flow as WooCommerce vendors — the vendor selects their preferred method (manual or CSV) during their own onboarding.++### Send the Invitation++To invite a vendor, navigate to **Vendors** in the admin dashboard.++++Click **Invite Vendor** in the top right corner to open the invitation form.++++Fill in the following fields:++- **Company Name or Brand Name** - how the vendor will be displayed in the admin dashboard.+- **Contact Person Email** - the work email address of the person who should receive the invitation.+- **Commission Rate** - the pre-agreed commission rate to be shared with the marketplace.++<Note>The commission rate can be different for each vendor and updated later from the vendor's profile.</Note>++Double-check the details and click **Send Invitation**. The newly invited vendor will appear in your list of vendors with a pending status.++++The vendor will receive an email at the specified address with a link to begin onboarding.++### Share the Invitation Link Manually++If the vendor doesn't receive the email, or they prefer a different communication channel, you can copy the invitation link and send it directly.++Click on the vendor in the list to open their vendor profile, navigate to the **Invitations** subtab, click the three-dot menu, and select **Copy invitation link**.++++### Cancel an Invitation++If you need to withdraw the invitation — whether the wrong contact was invited, the vendor's details need correcting, or the partnership ended before they began onboarding — navigate to the **Invitations** subtab as above, click the three-dot menu, and select **Delete**.++<Warning>Cancelling an invitation is irreversible. To re-invite the vendor later, you'll need to start the invitation flow from scratch.</Warning>++---++## Vendor Onboarding++This section is for the vendor. Once you've received the invitation from the marketplace owner, follow these steps to set up your vendor account and start adding products.++### 1. Accept the Invitation++You'll receive an email invitation from the marketplace owner with a link to get started. Click the link to be directed to your vendor account creation page.++### 2. Create Your Vendor Account++Fill in the sign-up form to create your vendor account, then click **Create Account**.++++You'll then be redirected to your new vendor dashboard, where you'll see a **Getting Started** checklist of onboarding tasks.++++### 3. Set Up Your Shop++Click on the **Connect or Create a Shop** task in the checklist, then click **Use CSV and/or Admin dashboard**.++++The task will be marked complete and you'll be ready to start adding products.++### 4. Add Your Products++Unlike vendors who connect Shopify or WooCommerce, you'll need to add products to your marketplace catalog yourself. You have two options:++- **Add products manually, one-by-one** — best for small catalogs or when you're testing things out. See [<u>Create a Product</u>](https://spreecommerce.org/docs/user/products/creating-products) for the full walkthrough of the product editor.+- **Upload products in bulk via CSV** — best for larger catalogs or when migrating from another platform. See [<u>Import Products</u>](https://spreecommerce.org/docs/user/manage-products/import-products) for a step-by-step guide to preparing and uploading your CSV file.++You can mix and match these methods as needed — for example, bulk-importing the initial catalog and then adding new products manually as they're released.++### 5. Complete Your Remaining Onboarding Tasks++With your shop set up, you'll still need to complete a few more tasks before you can start selling.++#### Add Billing Address++Your company's billing address is needed for vendor payouts and invoices. Click on the task in your checklist, fill in the form, and click **Save**.++++#### Connect Your Stripe Account++Stripe is used by the marketplace to process payments and send your payouts. To receive your earnings, you'll need to connect a Stripe account.++1. Click on **Connect Stripe Account** in your onboarding checklist.+2. Click **Connect your bank account** to be guided through Stripe's short onboarding process.+3. Follow the Stripe prompts to set up a new account or connect an existing one.++++An existing Stripe account isn't required — you can create one as part of this flow. The whole process usually takes around five minutes. Once connected, you'll receive payouts whenever you ship orders.++<Note>If you're not the one handling your company's financials, you can invite another team member to complete this step instead.</Note>++<Warning>Some marketplaces use payment providers other than Stripe. If that's the case, you'll be prompted to connect your bank account through a different flow — your marketplace owner will let you know the specifics.</Warning>++#### Add Returns Address++A returns address ensures customers know where to send returns. Click on the task in your checklist, enter your company's return address, and click **Save**.++++#### Set Shipping Rates++Since you're not connecting an external store, you'll need to add your shipping methods and rates manually.++Click on the **Set Shipping Rates** task, then click **Manage Shipping Rates** to be taken to the **Settings → Shipping** section of your vendor dashboard. Add each shipping method you'd like to offer along with its rate, then click **Confirm Shipping Rates** in the top right corner.++++<Note>You can edit existing shipping methods or add new ones at any time after onboarding is complete.</Note>++#### Add Policies++A clear returns policy builds customer trust, sets clear expectations, and helps prevent disputes over returns and refunds.++1. Click on **Add Policies** to be redirected to **Settings → Policies**.+2. Click on the policy you'd like to update to enter the editor.+3. Paste your policy into the text field.+4. Click **Save**.++++## Next Steps++Once onboarding is complete, your products will be sent to the marketplace owner for review. Once they're approved, they'll go live on the storefront, and you can manage your business directly from your Spree vendor dashboard.++For other vendor types, see [<u>Shopify Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-shopify) or [<u>WooCommerce Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-woocommerce).diff --git a/docs/v5/user/vendors/vendor-onboarding-shopify.mdx b/docs/v5/user/vendors/vendor-onboarding-shopify.mdxnew file mode 100644index 0000000000..40144ce128--- /dev/null+++ b/docs/v5/user/vendors/vendor-onboarding-shopify.mdx@@ -0,0 +1,214 @@+---+title: "Shopify Vendor Onboarding"+description: "Learn how to invite and onboard a Shopify-based vendor to your multi-vendor marketplace in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/vendors/vendor-onboarding-shopify"+---++<Warning>Shopify vendor onboarding is only available in Spree Enterprise Edition.</Warning>++<Note>This guide covers vendors who'll connect their Shopify store to your marketplace. For other vendor types, see [<u>WooCommerce Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-woocommerce) and [<u>Manual/CSV Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-manual).</Note>++Shopify is one of the most common platforms your prospective vendors will already be running on, so it's worth setting up a smooth, automated path for them to join your marketplace. With the right setup in place, a Shopify vendor can connect their store in just a few clicks — products, inventory, orders, and shipping all sync between Shopify and your marketplace automatically.++Onboarding a Shopify vendor has two distinct parts: a one-time **Admin Setup** that the marketplace owner completes per vendor in their Shopify Partners account and Spree admin, and a much shorter **Vendor Onboarding** flow that the vendor themselves completes after receiving the install link.++## Prerequisites++Before you can onboard Shopify vendors, you'll need:++- A **Shopify Partners account** — this is where you'll create the custom Shopify apps used to connect each vendor's store.+- The **`spree_multi_vendor` Enterprise gem** installed on your Spree instance.++### How Spree Connects to a Vendor's Shopify Store++Before you start, it's worth understanding how Spree's Shopify integration is structured — Shopify supports several different patterns for building and distributing apps, and we want to be explicit about which one applies here.++Spree connects each vendor's store using a **Custom App distributed via Custom Distribution** — Shopify's recommended path for apps built for specific, known stores (such as the vendors on your marketplace). You can read more in [<u>Shopify's Custom Apps overview</u>](https://help.shopify.com/en/manual/apps/about-apps#custom-apps).++Everything you need to set up is available **directly in the Shopify Partners UI**. You do not need to:++- Use the Shopify CLI+- Maintain a separate codebase for the Shopify app++This setup is repeated once per Shopify vendor — each vendor gets their own dedicated Custom App so that their store can be installed and authorized independently.++<Note>Spree's integration does not use the Shopify Sales Channel App pattern, despite some surface-level overlap.</Note>++---++## Admin Setup++This section is for the marketplace owner. It's a one-time setup per vendor — once complete, the vendor only needs to install the app and complete a few onboarding tasks.++### 1. Create the Shopify App++Each Shopify vendor requires their own dedicated app, created from your Shopify Partners account.++1. Sign in to your **Shopify Partners** account and open the **Dev Dashboard**.+2. Click **Create app**.+3. Give the app a name that identifies which vendor it's for. We recommend writing the name in kebab-case (lowercase words separated by hyphens), e.g., `example-vendor`.+4. You'll be redirected to the **Versions → Create version** page. Fill in the form using the values below:++ - **App name** - already pre-filled from the previous step.+ - **App URL** - `<app-base-url>/shopify/apps/<app-handle>` (e.g., `https://spree-marketplace.com/shopify/apps/example-vendor`).+ - The `<app-base-url>` should point to your store URL. If you have multiple stores, we recommend using the URL of the default store.+ - The `<app-handle>` can be set arbitrarily but must be unique across all your Shopify apps. We recommend using the app name from step 3 (already in kebab-case).+ - **Embed app in Shopify admin** - leave unchecked.+ - **Preferences URL** - leave empty.+ - **Webhooks API Version** - `2025-07`.+ - **Scopes** - paste the following list exactly:+ ```+ write_orders,read_inventory,read_products,read_fulfillments,read_locations,read_translations,read_locales,read_shipping+ ```+ - **Optional scopes** - leave empty.+ - **Use legacy install flow** - leave unchecked.+ - **Redirect URLs** - add both of the following:+ - `<app-base-url>/shopify/apps/<app-handle>/auth`+ - `<app-base-url>/shopify/apps/<app-handle>/auth_callback`++5. Click **Release** at the bottom of the form, then confirm in the modal that appears.++After completing these steps, you should see an overview of the version you just released.++++### 2. Get the App's Credentials++Spree needs the app's Client ID and Secret to authenticate against Shopify.++1. In the **Shopify Dev Dashboard**, select the app you just created.+2. Open the app's **Settings** page.+3. Copy and save both the **Client ID** and the **Secret**.++++### 3. Register the App in Spree++Now register the new Shopify app inside your Spree admin so the marketplace can communicate with it.++1. In the Spree admin dashboard, navigate to **Settings → Shopify Apps**.++++2. Click **New Shopify App** in the top right corner.+3. Fill in the form and click **Create**:+ - **Handle** - must match the `<app-handle>` you used in step 1 (e.g., `example-vendor`).+ - **Name** - can be anything, but we recommend matching the handle for consistency.+ - **Client ID** - paste the Client ID from step 2.+ - **Secret** - paste the Secret from step 2.++++### 4. Generate the Install Link++With the app created and connected to Spree, the next step is to generate the install link the vendor will use to connect their store.++1. From the app's **Overview** page in the **Shopify Partner dashboard**, click **Select distribution method**.++++2. Choose **Custom Distribution** and click **Select**. Confirm in the modal.++++3. Fill in the Distribution form:+ - **Store domain** - the vendor's Shopify store domain, formatted as either `<shopify-domain>.myshopify.com` or `admin.shopify.com/store/<shopify-domain>` (e.g., `admin.shopify.com/store/jessicas-gym`).+ - **Allow multi-store install for one Plus organization** - leave this unchecked.+4. Click **Generate link** and confirm in the modal.+5. Copy the **install link** and save it — you'll send this to the vendor in step 5.++++### 5. Share the Install Link with the Vendor++Send the install link you saved in step 4 to the vendor through any communication channel — email, Slack, or whatever you normally use. From here, the rest of the flow is on the vendor — see the **Vendor Onboarding** section below for what they'll experience.++<Note>Vendor accounts are set up with the Shopify store owner's email address. If you're connecting multiple Shopify stores that share an owner email, each store will need a unique email set under **Shopify Store Settings → General → Store details**.</Note>++<Warning>If you're testing the flow yourself, make sure you're signed out of the marketplace owner account before opening the install link — otherwise installation will fail. If that happens, simply open the install link again.</Warning>++---++## Vendor Onboarding++This section is for the vendor. Once you've received the install link from the marketplace owner, follow these steps to connect your Shopify store and complete your onboarding.++### 1. Install the Shopify App++1. Open the install link the marketplace owner sent you.+2. Log in to Shopify and select the store you'll be connecting to the marketplace.++++3. Accept the app installation.++++### 2. Create Your Vendor Account++After accepting the installation, you'll be redirected to a Spree onboarding screen and asked to create a vendor account.++++Fill in the form and submit. A few minutes after submitting, your Shopify products will start appearing in your Spree vendor dashboard.++### 3. Complete Your Onboarding Tasks++When you arrive at your vendor dashboard, you'll see a **Getting Started** checklist. Most tasks are auto-completed for Shopify vendors thanks to the integration, but a few still need your attention.++++#### Auto-Completed Tasks++The following tasks are marked complete automatically when you install the app — just verify the imported information is correct:++- **Connect or Create a Shop** — completed by the app installation itself.+- **Add Billing Address** — imported from your Shopify store's billing details.+- **Add Returns Address** — imported from your Shopify store's address.+- **Add Returns Policy** — imported from your Shopify store, provided you have a returns policy configured there.++#### Confirm Shipping Rates++Your Shopify shipping methods and rates are synced automatically, but you still need to confirm them to mark this task complete.++Navigate to **Settings → Shipping** in your vendor dashboard and click **Confirm Shipping Rates** in the top right corner.++++<Note>You can edit existing shipping methods or add new ones at any time before or after onboarding is complete.</Note>++#### Connect Your Stripe Account++<Warning>Some marketplaces use payment providers other than Stripe. If that's the case, you'll be prompted to connect your bank account through a different flow — your marketplace owner will let you know the specifics.</Warning>++Stripe is used by the marketplace to process payments and send your payouts. To receive your earnings, you'll need to connect a Stripe account.++1. Click on **Connect Stripe Account** in your onboarding checklist.+2. Click **Connect your bank account** to be guided through Stripe's short onboarding process.+3. Follow the Stripe prompts to set up a new account or connect an existing one.++++An existing Stripe account isn't required — you can create one as part of this flow. The whole process usually takes around five minutes. Once connected, you'll receive payouts whenever you ship orders.++<Note>If you're not the one handling your company's financials, you can invite another team member to complete this step instead.</Note>++---++## What Syncs Between Shopify and the Marketplace++Once your Shopify store is connected, the following data syncs automatically:++- **Active products** are imported into the marketplace catalog.+- **Inventory levels** sync in both directions in real-time.+- **Shipping methods and rates** sync from Shopify to the marketplace.+- **Orders** placed on the marketplace appear in your Shopify dashboard for fulfillment, just like normal Shopify orders.+- **Fulfillment status and shipment tracking** sync back to the marketplace and trigger customer notifications automatically.+- **Price updates** made in Shopify sync to the marketplace.+- **Content updates** (descriptions, images) sync to the marketplace, unless the marketplace owner has edited them.++## Next Steps++Once onboarding is complete, your products will be sent to the marketplace owner for review. Once they're approved, they'll go live on the storefront, and you can manage your business primarily from your Shopify dashboard.++For other vendor types, see [<u>WooCommerce Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-woocommerce) or [<u>Manual/CSV Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-manual).diff --git a/docs/v5/user/vendors/vendor-onboarding-woocommerce.mdx b/docs/v5/user/vendors/vendor-onboarding-woocommerce.mdxnew file mode 100644index 0000000000..ececd7d5a3--- /dev/null+++ b/docs/v5/user/vendors/vendor-onboarding-woocommerce.mdx@@ -0,0 +1,174 @@+---+title: "WooCommerce Vendor Onboarding"+description: "Learn how to invite and onboard a WooCommerce-based vendor to your multi-vendor marketplace in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/vendors/vendor-onboarding-woocommerce"+---++<Warning>WooCommerce vendor onboarding is only available in Spree Enterprise Edition.</Warning>++<Note>This guide covers vendors who'll connect their WooCommerce store to your marketplace. For other vendor types, see [<u>Shopify Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-shopify) and [<u>Manual/CSV Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-manual).</Note>++WooCommerce is one of the most widely used ecommerce platforms in the world, so it's worth making it easy for WooCommerce-based vendors to join your marketplace. Once connected, a vendor's products, inventory, orders, and shipping flow automatically between their WooCommerce store and your marketplace — no manual reconciliation required.++Onboarding a WooCommerce vendor has two distinct parts: an **Admin Setup** that the marketplace owner completes by sending an invitation, and a **Vendor Onboarding** flow that the vendor themselves completes after receiving the invite.++## Prerequisites++Before you can onboard WooCommerce vendors, you'll need:++- The **`spree_multi_vendor` Enterprise gem** installed on your Spree instance.++---++## Admin Setup++This section is for the marketplace owner. Inviting a WooCommerce vendor uses the same invitation flow as Manual/CSV vendors — the vendor chooses WooCommerce as their connection method during their own onboarding.++### Send the Invitation++To invite a vendor, navigate to **Vendors** in the admin dashboard.++++Click **Invite Vendor** in the top right corner to open the invitation form.++++Fill in the following fields:++- **Company Name or Brand Name** - how the vendor will be displayed in the admin dashboard.+- **Contact Person Email** - the work email address of the person who should receive the invitation.+- **Commission Rate** - the pre-agreed commission rate to be shared with the marketplace.++<Note>The commission rate can be different for each vendor and updated later from the vendor's profile.</Note>++Double-check the details and click **Send Invitation**. The newly invited vendor will appear in your list of vendors with a pending status.++++The vendor will receive an email at the specified address with a link to begin onboarding.++### Share the Invitation Link Manually++If the vendor doesn't receive the email, or they prefer a different communication channel, you can copy the invitation link and send it directly.++Click on the vendor in the list to open their vendor profile, navigate to the **Invitations** subtab, click the three-dot menu, and select **Copy invitation link**.++++### Cancel an Invitation++If you need to withdraw the invitation — whether the wrong contact was invited, the vendor's details need correcting, or the partnership ended before they began onboarding — navigate to the **Invitations** subtab as above, click the three-dot menu, and select **Delete**.++<Warning>Cancelling an invitation is irreversible. To re-invite the vendor later, you'll need to start the invitation flow from scratch.</Warning>++---++## Vendor Onboarding++This section is for the vendor. Once you've received the invitation from the marketplace owner, follow these steps to connect your WooCommerce store and complete your onboarding.++### 1. Accept the Invitation++You'll receive an email invitation from the marketplace owner with a link to get started. Click the link to be directed to your vendor account creation page.++### 2. Create Your Vendor Account++Fill in the sign-up form to create your vendor account, then click **Create Account**.++++You'll then be redirected to your new vendor dashboard, where you'll see a **Getting Started** checklist of onboarding tasks.++++### 3. Connect Your WooCommerce Store++Click on the **Connect or Create a Shop** task in the checklist, then click **WooCommerce**.++++A popup will appear asking for your WooCommerce store's URL.++++Enter your store URL and click **Continue**. You'll be redirected to a page asking you to approve the marketplace's connection to your store.++++Click **Approve**. You'll be redirected back to your vendor dashboard, and the task will be marked complete.++A few minutes after connecting, your WooCommerce products will start appearing in your Spree vendor dashboard.++### 4. Complete Your Remaining Onboarding Tasks++With your store connected, you'll still need to complete a few more tasks before you can start selling.++#### Add Billing Address++Your company's billing address is needed for vendor payouts and invoices. Click on the task in your checklist, fill in the form, and click **Save**.++++#### Connect Your Stripe Account++Stripe is used by the marketplace to process payments and send your payouts. To receive your earnings, you'll need to connect a Stripe account.++1. Click on **Connect Stripe Account** in your onboarding checklist.+2. Click **Connect your bank account** to be guided through Stripe's short onboarding process.+3. Follow the Stripe prompts to set up a new account or connect an existing one.++++An existing Stripe account isn't required — you can create one as part of this flow. The whole process usually takes around five minutes. Once connected, you'll receive payouts whenever you ship orders.++<Note>If you're not the one handling your company's financials, you can invite another team member to complete this step instead.</Note>++<Warning>Some marketplaces use payment providers other than Stripe. If that's the case, you'll be prompted to connect your bank account through a different flow — your marketplace owner will let you know the specifics.</Warning>++#### Add Returns Address++A returns address ensures customers know where to send returns. Click on the task in your checklist, enter your company's return address, and click **Save**.++++#### Set Shipping Rates++Your WooCommerce shipping methods are synced to the marketplace automatically, but rates aren't — you'll need to set them manually.++Click on the **Set Shipping Rates** task, then click **Manage Shipping Rates** to be taken to the **Settings → Shipping** section of your vendor dashboard. Set the rate for each shipping method, then click **Confirm Shipping Rates** in the top right corner.++++<Note>You can edit existing shipping methods or add new ones at any time after onboarding is complete.</Note>++#### Add Policies++Clear policies build customer trust, sets clear expectations, and helps prevent disputes over shipping, returns and refunds.++1. Click on **Add Policies** in your onboarding checklist to be redirected to **Settings → Policies**.+2. Click on the policy you like to update.+3. Add content to the field in the policy editor.+4. Click **Save**.++++---++## What Syncs Between WooCommerce and the Marketplace++Once your WooCommerce store is connected, the following data syncs automatically:++- **Active products** are imported into the marketplace catalog.+- **Inventory levels** sync in both directions in real-time.+- **Shipping methods** sync from WooCommerce to the marketplace — note that **rates do not sync** and must be set manually in your vendor dashboard.+- **Orders** placed on the marketplace appear in your WooCommerce dashboard for fulfillment, just like normal WooCommerce orders.+- **Fulfillment status and shipment tracking** sync back to the marketplace and trigger customer notifications automatically.+- **Price updates** made in WooCommerce sync to the marketplace.+- **Content updates** (descriptions, images) sync to the marketplace, unless the marketplace owner has edited them.++## Next Steps++Once onboarding is complete, your products will be sent to the marketplace owner for review. Once they're approved, they'll go live on the storefront, and you can manage your business primarily from your WooCommerce dashboard.++For other vendor types, see [<u>Shopify Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-shopify) or [<u>Manual/CSV Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-manual).diff --git a/docs/v5/user/vendors/vendor-payouts.mdx b/docs/v5/user/vendors/vendor-payouts.mdxnew file mode 100644index 0000000000..59b02a115a--- /dev/null+++ b/docs/v5/user/vendors/vendor-payouts.mdx@@ -0,0 +1,60 @@+---+title: "Vendor Payouts"+description: "Learn how to set and override vendor payout schedules across your multi-vendor marketplace in Spree Commerce."+canonical: "https://spreecommerce.org/docs/user/vendors/vendor-payouts"+---++<Warning>Multi-vendor capabilities are only available in Spree Enterprise Edition.</Warning>++<Warning>Vendor payout scheduling is a Stripe Connect feature. If your marketplace is configured with a different payment provider, the payout schedule controls described below won't be available in your admin or vendor dashboards.</Warning>++Vendor payouts are how your vendors actually receive the money they've earned from sales on your marketplace. Spree's payout flow runs through Stripe Connect, which means once a vendor has connected their Stripe account during onboarding, they'll be paid automatically on whatever schedule you've configured — no manual transfers, no chasing invoices.++Like with [<u>commission rates</u>](https://spreecommerce.org/docs/user/vendors/commission-rates), one fixed schedule rarely suits every vendor. Some may want frequent payouts to manage cash flow, others may prefer larger, less frequent transfers. Spree lets you set a marketplace-wide default and override it per vendor as needed.++## 1. Default Marketplace Payout Schedule++The default payout schedule applies to every vendor whose schedule is set to **Use marketplace default interval**. It's configured under **Settings → Marketplace** and serves as the fallback for everyone who hasn't opted into a custom schedule.++See [<u>Marketplace Configuration</u>](https://spreecommerce.org/docs/user/settings/marketplace) for details on setting and updating the default schedule.++<Note>Changing the default also updates the payout schedule for any existing vendors who are still on the marketplace default. Vendors who've chosen a specific schedule of their own won't be affected.</Note>++## 2. Vendor-Specific Payout Schedule++You can override the payout schedule for individual vendors directly from their vendor profile — useful when a particular vendor has cash flow needs that differ from the rest of your marketplace.++Navigate to **Vendors** in the admin dashboard and click on the vendor you'd like to update.++++Scroll down to the **Payments & Payouts** section of the vendor profile and choose a payout schedule from the dropdown.++++The available options are:++- **Use marketplace default interval** - the vendor follows whatever default is configured under Settings → Marketplace.+- **Daily** - payouts are issued every business day.+- **Weekly** - payouts are issued once per week.+- **Bi-weekly** - payouts are issued every two weeks.+- **Monthly** - payouts are issued once per month.++Click **Update** at the bottom of the page to save your changes.++<Note>If you set a vendor to a specific schedule (anything other than **Use marketplace default interval**), future changes to the marketplace default will no longer affect them. To bring them back in line, set them back to **Use marketplace default interval**.</Note>++## Which Schedule Applies?++When a payout is processed, Spree applies the most specific schedule available, in the following order:++1. **Vendor-specific schedule** — if set to a specific interval, this wins.+2. **Marketplace default schedule** — used whenever a vendor is set to **Use marketplace default interval**.++## Next Steps++For more on how vendors connect their Stripe accounts during onboarding (which is what makes automated payouts possible), see the relevant onboarding doc:++- [<u>Shopify Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-shopify)+- [<u>WooCommerce Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-woocommerce)+- [<u>Manual/CSV Vendor Onboarding</u>](https://spreecommerce.org/docs/user/vendors/vendor-onboarding-manual)diff --git a/docs/v5/user/what-is-spree-commerce.mdx b/docs/v5/user/what-is-spree-commerce.mdxnew file mode 100644index 0000000000..7ba692c699--- /dev/null+++ b/docs/v5/user/what-is-spree-commerce.mdx@@ -0,0 +1,53 @@+---+title: "What is Spree Commerce"+description: "What is Spree Commerce? What can I build with Spree?"+canonical: "https://spreecommerce.org/docs/user/what-is-spree-commerce"+---++<img alt="Spree Commerce - Open Source e-commerce platform" classname="block dark:hidden" src="https://raw.githubusercontent.com/spree/spree/e4ee6636d9a31c73761b0c76662d15b0f9899ecb/docs/images/Spree%20Commerce%20open-source%20eCommerce%20platform%20API%20headless%20Next.js.webp" />++## About Spree Commerce++[Spree Commerce](https://spreecommerce.org/) is an API-first, [open-source eCommerce platform](https://github.com/spree/spree) built for fast growing businesses and enterprises.++Spree allows you to build [B2B eCommerce](https://spreecommerce.org/use-cases/headless-b2b-ecommerce/), [multi-store](https://spreecommerce.org/multi-store-ecommerce/), [multi-region](https://spreecommerce.org/multi-region-ecommerce/), [multi-vendor marketplace](https://spreecommerce.org/marketplace-ecommerce/), and [multi-tenant commerce](https://spreecommerce.org/multi-tenant-white-label-ecommerce/) - and you can combine them to match your exact business model.++If SaaS solutions don't give you the control and flexibility your business needs, Spree is the answer.++Spree is trusted by thousands of businesses around the world, including GoDaddy, Huckberry, Craftsman, DieHard, Kenmore, Paccar, Maisonette, Goop, Garmentory, and Blue Bottle Coffee.++Spree comes in two flavors - as a free Community Edition or as a paid Enterprise Edition.++## Community Edition vs Enterprise Edition++<CardGroup cols={2}>+ <Card title="Community Edition" href="https://github.com/spree/spree/">+ Spree Community Edition is free. It's the DIY version of Spree. It comes with community support only.+ </Card>++ <Card title="Enterprise Edition" href="https://spreecommerce.org/enterprise/">+ Spree Enterprise Edition comes with more features, more security, more integrations and enterprise support.+ </Card>+</CardGroup>++TL;DR The Community Edition gives you freedom. The Enterprise Edition saves you time.++So what sets both versions apart? Here's a [feature comparison](https://spreecommerce.org/enterprise/) of the two editions and here's an [in-depth overview](https://spreecommerce.org/spree-commerce-version-comparison-community-edition-vs-enterprise-edition/).++## Looking for Developer Documentation?++This Spree user documentation is intended for business owners and site administrators of Spree e-commerce sites. Everything you need to know to configure and manage your Spree store can be found here.++If you are a developer, you may find the [Developer Guides](/developer) to be of benefit to you, though we strongly urge you to read through both sets of guides.++BTW Give Spree a [GitHub Star](https://github.com/spree/spree)<Icon icon="star" iconType="solid" color="#FFD43B" />, why don't ya?++Thank you for supporting Spree open-source! <Icon icon="heart" iconType="solid" color="#FF0000" />++## Join Spree Discord++To join the Spree Community and over 6000+ Spree users and developers, please join our [Discord](https://discord.spreecommerce.org/)++## Contact us++If you'd like to get in touch to share your feedback, request features, or start a new project, please fill out this contact form: [https://spreecommerce.org/get-started/](https://spreecommerce.org/get-started/)diff --git a/docs/v6/developer/core-concepts/orders.mdx b/docs/v6/developer/core-concepts/orders.mdxdeleted file mode 100644index 54807f4363..0000000000--- a/docs/v6/developer/core-concepts/orders.mdx+++ /dev/null@@ -1,166 +0,0 @@-----title: Orders-description: How Spree models orders — a permanent record created by completing a cart, with separate payment and delivery statuses.------## Overview--An order is a placed purchase. It's created by completing a [Cart](/v6/developer/core-concepts/carts) and holds its own copy of everything the customer agreed to — items, prices, taxes, discounts and delivery.--```mermaid-erDiagram- Order ||--o{ LineItem : "has many"- Order ||--o{ Fulfillment : "has many"- Order ||--o{ Payment : "has many"- Order ||--o{ Return : "has many"- Order }o--|| Cart : "created from"- Order }o--|| Customer : "belongs to"-- Order {- string number- string payment_status- string fulfillment_status- string total- datetime completed_at- }-```--## Order attributes--| Attribute | Description |-|---|---|-| `id` | Order ID, e.g. `or_86Rf07xd4z` |-| `number` | Order number shown to customers, e.g. `R1001` — sequential by default, [customizable](/v6/developer/how-to/custom-document-numbers) |-| `cart_id` | The cart this order came from |-| `email` | Customer's email address |-| `currency` | Order currency, e.g. `USD` |-| `total_quantity` | Total number of items |-| `payment_status` | See [statuses](#statuses) below |-| `fulfillment_status` | See [statuses](#statuses) below |-| `item_total` / `display_item_total` | Sum of line item prices |-| `delivery_total` / `display_delivery_total` | Delivery cost |-| `tax_total` / `display_tax_total` | Total tax |-| `discount_total` / `display_discount_total` | Total discount |-| `total` / `display_total` | Order total |-| `amount_due` / `display_amount_due` | Still outstanding |-| `completed_at` | When the order was placed |--Every amount comes in two forms: `total` is the raw value (`"135.60"`) and [`display_total` is formatted for the currency](/api-reference/store-api/monetary-amounts) (`"$135.60"`). Render the `display_` one.--## Statuses--An order tracks payment and delivery separately, because they genuinely move at different speeds. An order can be paid but not yet sent, or sent and later partly refunded.--**`payment_status`**--| Value | Meaning |-|---|---|-| `none` | Nothing paid or authorized yet |-| `authorized` | Money is held but not taken |-| `partially_paid` | Some of the total has been taken |-| `paid` | Fully paid |-| `partially_refunded` | Some money returned |-| `refunded` | Everything returned |-| `overcharged` | More was taken than the order total |-| `voided` | The hold was released without taking money |--**`fulfillment_status`**--| Value | Meaning |-|---|---|-| `unfulfilled` | Nothing has gone out yet |-| `backorder` | Waiting on stock |-| `partial` | Some of it has gone out |-| `fulfilled` | Everything has gone out |-| `delivered` | The customer has all of it |-| `canceled` | Nothing will be sent |--A canceled parcel is ignored while others are still live, so an order whose second parcel was recalled is described by the first.--Both are worked out automatically from the order's payments, refunds and fulfillments. You change an order's status by acting on those — taking a payment, sending a parcel, issuing a refund — never by setting the status yourself.--## Reading an order--A customer can fetch their own order; guests use the order token they got at checkout.--<CodeGroup>--```typescript Store SDK-// A single order-const order = await client.orders.get('or_xxx')--// The signed-in customer's order history-const orders = await client.customers.orders.list({ per_page: 20 })-```--```bash cURL-curl 'https://api.mystore.com/api/v3/store/orders/or_xxx' \- -H 'X-Spree-API-Key: pk_xxx' \- -H 'X-Spree-Token: order_token_xxx'-```--</CodeGroup>--## Managing orders--Back-office work happens through the Admin API.--<CodeGroup>--```typescript Admin SDK-// Find orders needing attention-const orders = await adminClient.orders.list({- filter: { payment_status_eq: 'paid', fulfillment_status_eq: 'unfulfilled' },-})--// Cancel an order-await adminClient.orders.cancel('or_xxx', {- reason: 'customer',- restock_items: true,- refund_payments: true,-})--// Take an authorized payment-await adminClient.orders.payments.capture('or_xxx', 'pay_xxx')--// Refund against a specific payment-await adminClient.orders.refunds.create('or_xxx', {- payment_id: 'pay_xxx',- amount: '25.00',-})-```--```bash cURL-curl 'https://api.mystore.com/api/v3/admin/orders?filter[payment_status_eq]=paid' \- -H 'X-Spree-API-Key: sk_xxx'--curl -X PATCH 'https://api.mystore.com/api/v3/admin/orders/or_xxx/cancel' \- -H 'X-Spree-API-Key: sk_xxx' \- -H 'Content-Type: application/json' \- -d '{ "reason": "customer", "restock_items": true }'-```--</CodeGroup>--Canceling records who canceled and why, puts stock back, and settles any payments.--## Orders don't change quietly--A placed order is meant to stay put. Its items and prices are written when the cart is completed and then left alone, so an order keeps saying what the customer actually agreed to — even if a product's price changes the next day.--Where admin edits are allowed, totals are re-added from the order's existing rows rather than worked out again from scratch. Editing an order must never quietly re-apply today's promotions and hand the customer a different discount than the one they accepted.--## Money on an order--Tax, discounts and fees are kept as separate records, so you can ask what tax was charged without picking through a mixed list. See [Taxes, Discounts & Fees](/v6/developer/core-concepts/taxes-discounts-fees).--## Events--Orders publish [events](/developer/core-concepts/events) — `order.placed`, `order.canceled`, `order.paid` and more — which also reach [webhooks](/developer/core-concepts/webhooks). This is the right way to push orders to another system, trigger fulfillment, or start an email flow.--## Related--- [Carts](/v6/developer/core-concepts/carts) — shopping and checkout-- [Fulfillments](/v6/developer/core-concepts/fulfillments) — getting items to the customer-- [Returns, Exchanges & Claims](/v6/developer/core-concepts/returns-exchanges-claims) — after the sale-- [Payments](/developer/core-concepts/payments) — payment methods and processingdiff --git a/docs/v6/developer/core-concepts/promotions.mdx b/docs/v6/developer/core-concepts/promotions.mdxdeleted file mode 100644index de7235fb8d..0000000000--- a/docs/v6/developer/core-concepts/promotions.mdx+++ /dev/null@@ -1,260 +0,0 @@-----title: Promotions-description: Build percentage and fixed-amount discounts, free shipping, BOGO offers, and coupon codes with Spree's rule and action-based promotion system.------## Overview--Promotions give money off an order — a percentage off, free shipping, or free items added to the cart. A promotion is a campaign definition: **rules** decide when it applies, **actions** decide what it does. When a promotion applies, its actions write [Discount](/v6/developer/core-concepts/taxes-discounts-fees#discounts) rows on the order.--```mermaid-erDiagram- Promotion {- string name- string kind- string code- datetime starts_at- datetime expires_at- integer usage_limit- string match_policy- }-- PromotionRule {- string type- text preferences- }-- PromotionAction {- string type- }-- CouponCode {- string code- string state- }-- Discount {- string label- string kind- string code- string amount- }-- Promotion ||--o{ PromotionRule : "has many"- Promotion ||--o{ PromotionAction : "has many"- Promotion ||--o{ CouponCode : "has many"- PromotionAction ||--o{ Discount : "writes"- Order ||--o{ Discount : "has many"-```--Promotions can be activated in two ways:--- **Automatic promotions** — applied on their own when the rules are met (e.g. free shipping on orders over $50)-- **Coupon code promotions** — applied when a customer enters a valid code during checkout--### How discounts are recorded--Each applied promotion becomes one or more Discount rows on the order — on a specific line item or on a fulfillment, never a loose adjustment. Each row keeps a copy of the coupon code and the configured value ("10% off"), so the order still tells the whole story even if the promotion is deleted later.--Two things follow from this design:--- **Only winners are stored.** When several promotions compete for the same item, Spree picks the one that saves the customer the most and writes only that one. Losing candidates are recomputed on every cart change, so a promotion that loses today can win tomorrow without any bookkeeping.-- **A discount on the whole order is shared out across the items.** If a customer later returns one item, Spree knows exactly how much of the discount belonged to it.--## Promotion Attributes--| Attribute | Description | Example |-|-----------|-------------|---------|-| `name` | The name of the promotion | Summer Sale |-| `description` | Brief description (max 255 chars) | 20% off all summer items |-| `kind` | Type: `coupon_code` or `automatic` | `automatic` |-| `starts_at` | When the promotion becomes active | 2026-06-01 00:00:00 |-| `expires_at` | When the promotion expires | 2026-09-01 23:59:59 |-| `usage_limit` | Max times the promotion can be used | 500 |-| `match_policy` | How rules are evaluated: `all` or `any` | `all` |-| `advertise` | Whether to display on storefront | `true` |--### Multi-Code Promotions--For promotions that need unique codes per customer (e.g. influencer campaigns), Spree supports bulk code generation:--| Attribute | Description | Example |-|-----------|-------------|---------|-| `multi_codes` | Enable bulk code generation | `true` |-| `number_of_codes` | How many codes to generate | 1000 |-| `code_prefix` | Prefix for generated codes | `SUMMER` |--Generated codes follow the pattern `{prefix}{random}`, e.g. `SUMMER22A0F62A230BD919`.--## Rules--Rules decide when a promotion is eligible. You can combine multiple rules and configure whether **all** must match or **any** is enough (via `match_policy`).--| Rule | Applies when |-|---|---|-| **FirstOrder** | It's the customer's first order (checked by account and email) |-| **ItemTotal** | The order subtotal is within configured minimum/maximum thresholds |-| **Product** | Specific products are in the order (`any` / `all` / `none` match policy) |-| **Category** | Products from specific categories are in the order — child categories count |-| **OptionValue** | Products with specific option values (size, color) are in the order |-| **User** | The customer is one of the listed accounts |-| **UserLoggedIn** | The customer is logged in |-| **OneUsePerUser** | The customer hasn't used this promotion before |-| **CustomerGroup** | The customer belongs to one of the configured customer groups |-| **Country** | The order ships to a specific country |-| **Currency** | The order is in a specific currency |-| **Channel** | The order was placed through one of the configured [channels](/developer/core-concepts/channels) |-| **Market** | The order belongs to one of the configured [markets](/developer/core-concepts/markets) |--You can also [build your own rules](/v6/developer/how-to/custom-promotion) for business-specific conditions.--## Actions--Actions define what happens when a promotion applies.--### CreateAdjustment--A discount on the whole order. The amount is distributed proportionally across the line items — there is no single order-level row, so per-item reporting and partial returns always know their share.--**Default calculator:** `FlatPercentItemTotal` (percentage off the order). Also available: `FlatRate`, `FlexiRate`, `TieredFlatRate`, `TieredPercent`.--**Use case:** "10% off your order", "$20 off orders over $100".--### CreateItemAdjustments--A discount on individual line items. Only items that match the promotion's rules receive it — if a Category rule says "Electronics", only electronics are discounted.--**Default calculator:** `PercentOnLineItem` (percentage off each item).--**Use case:** "15% off shoes", "Buy 2+ shirts get 10% off each".--### FreeShipping--Writes a discount on each fulfillment covering its delivery cost. The row is kept even when the cost is zero — its presence is what marks the order as having free shipping.--**Use case:** "Free shipping on orders over $75", "Free shipping with code FREESHIP".--### CreateLineItems--Adds specified products to the cart when the promotion is eligible, checking stock first. Items are not removed automatically if eligibility is lost — customers remove them manually.--**Use case:** "Free gift with purchase", "Spend $100 get a free sample".--## Managing Promotions--Create and manage promotions via the [Admin API](/api-reference/admin-api/introduction). Rules and actions can be supplied inline on create — each is a `{ type, preferences }` draft using the rule and action types described above:--<CodeGroup>--```typescript Admin SDK-import { createAdminClient } from '@spree/admin-sdk'--const client = createAdminClient({- baseUrl: 'https://store.example.com',- secretKey: 'sk_xxx',-})--// "20% off orders over $100 with code SUMMER20"-const promotion = await client.promotions.create({- name: 'Summer Sale',- code: 'SUMMER20',- kind: 'coupon_code',- rules: [{ type: 'item_total', preferences: { amount_min: 100 } }],- actions: [- {- type: 'create_adjustment',- calculator: { type: 'flat_percent_item_total', preferences: { flat_percent: 20 } },- },- ],-})-```--```bash CLI-spree api post /promotions -d '{- "name": "Summer Sale",- "code": "SUMMER20",- "kind": "coupon_code",- "rules": [{ "type": "item_total", "preferences": { "amount_min": 100 } }]-}'-```--</CodeGroup>--You can also add rules and actions to an existing promotion, or update and remove the promotion itself:--<CodeGroup>--```typescript Admin SDK-await client.promotions.rules.create('promo_xxx', {- type: 'first_order',-})-await client.promotions.update('promo_xxx', { expires_at: '2026-09-01T00:00:00Z' })-await client.promotions.delete('promo_xxx')-```--```bash CLI-spree api post /promotions/promo_xxx/promotion_rules -d '{"type": "first_order"}'-spree api patch /promotions/promo_xxx -d '{"expires_at": "2026-09-01T00:00:00Z"}'-```--</CodeGroup>--The available rule and action types — including any custom ones you register — are discoverable at `/api/v3/admin/promotion_rules/types` and `/api/v3/admin/promotion_actions/types`, together with their preference schemas. The dashboard's promotion editor is built on these endpoints, so custom types show up there without any UI work.--<Note>-Deleting a promotion doesn't disturb the orders that used it. Their discount rows stay, keeping the code and value they were created with — only the link back to the promotion is cleared.-</Note>--## Coupon Codes--Coupon codes track promotion usage and can be single-use or multi-use.--- **Single code** — set the `code` attribute on the promotion; `usage_limit` controls how many times it can be redeemed.-- **Multi-code** — bulk-generated codes each track their own state (`unused` / `used`).--Customers apply codes on the cart via the Store API:--<CodeGroup>--```typescript Store SDK-// Apply a discount code to the cart-const cart = await client.carts.discountCodes.apply('cart_abc123', 'SUMMER20', {- spreeToken: '<token>',-})--// Remove a discount code from the cart-await client.carts.discountCodes.remove('cart_abc123', 'SUMMER20', {- spreeToken: '<token>',-})-```--```bash cURL-# Apply a coupon code-curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_abc123/discount_codes' \- -H 'X-Spree-API-Key: pk_xxx' \- -H 'X-Spree-Token: <token>' \- -H 'Content-Type: application/json' \- -d '{ "code": "SUMMER20" }'-```--</CodeGroup>--The returned cart already carries the updated discounts and totals. If the cart doesn't qualify yet — say the code needs a $100 minimum and the cart holds $80 — the code stays on the cart and the discount activates on its own the moment the cart qualifies.--Automatic promotions need no customer action at all — they are evaluated on every cart change.--## Promotion Flow--1. **Cart change** — every change to a cart (item added, address entered, code applied) triggers a recalculation-2. **Eligibility** — each connected promotion is checked: active dates, usage limits, then rules per `match_policy`-3. **Competition** — candidate discounts are computed for every eligible promotion; per item, per fulfillment, and order-wide, the largest saving wins-4. **Persistence** — winning discounts are written as rows; anything stale from the previous pass is removed; tax is then estimated on the discounted amounts-5. **Placement** — once the order is placed, its discount rows are frozen; usage counts are recorded against the promotion--## Related Documentation--- [Taxes, Discounts & Fees](/v6/developer/core-concepts/taxes-discounts-fees) — the Discount rows promotions write, and manual discounts-- [Build Custom Promotion Rules & Actions](/v6/developer/how-to/custom-promotion) — step-by-step guide to custom rules, actions and adjusters-- [Calculators](/developer/core-concepts/calculators) — promotion calculators-- [Carts](/v6/developer/core-concepts/carts) — the cart lifecycle promotions act on-- [Admin SDK Resources](/developer/sdk/admin/resources) — the `client.promotions.*` resource-client pattern used abovediff --git a/docs/v6/developer/customization/configuration.mdx b/docs/v6/developer/customization/configuration.mdxdeleted file mode 100644index bd9425ee71..0000000000--- a/docs/v6/developer/customization/configuration.mdx+++ /dev/null@@ -1,229 +0,0 @@-----title: Configuration-description: Every global Spree setting that is actually read by Spree 6 — grouped by area, with defaults and what each one 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.--```ruby config/initializers/spree.rb-Spree.config do |config|- config.minimum_password_length = 10- config.allow_empty_price_amount = true-end-```--<Note>-Restart your Rails server after editing the initializer.-</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.--| Setting | Environment variable | What it configures |-|---|---|---|-| `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`. |--This page lists only settings Spree 6 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.--They were global before Spree 6. The global versions still exist for one release but are no longer read, so setting one in the initializer changes nothing — run `bin/rake spree:store_settings:backfill_from_config` during the upgrade 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"-```--Before Spree 6 this was two separate booleans, `auto_capture` and `auto_capture_on_dispatch`, which could contradict each other. Two upgrade tasks carry existing installs 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.--## Checkout and payments--| Setting | 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. |--## Carts and stock reservations--| Setting | 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. |--## Products and pricing--| Setting | 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. |--## Addresses--| Setting | Default | What it does |-|---|---|---|-| `geocode_addresses` | `true` | Looks up latitude and longitude for saved addresses. |--## Media--| Setting | 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. |--## Promotions and gift cards--| Setting | 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. |--## Accounts and passwords--| Setting | 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. |--## Imports and events--| Setting | 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--API settings live on their own configuration object:--```ruby config/initializers/spree.rb-Spree::Api::Config.jwt_expiration = 1800-```--### Authentication--| Setting | 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. |--### Rate limits--| Setting | 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 |-|---|---|---|-| `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 6 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](/v6/developer/core-concepts/returns-exchanges-claims#processing-a-return) |-| `expedited_exchanges` | [Exchanges](/v6/developer/core-concepts/returns-exchanges-claims) |-| `expedited_exchanges_days_window` | [Exchanges](/v6/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 in Spree 6, 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 removed in Spree 6--These were deprecated in Spree 5 and 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](/v6/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. |--## Related--- [Model preferences](/developer/customization/model-preferences) — per-record settings-- [Services & Workflows](/developer/customization/workflows) — changing behavior rather than settingsdiff --git a/docs/v6/developer/customization/permissions.mdx b/docs/v6/developer/customization/permissions.mdxdeleted file mode 100644index 2dafadb918..0000000000--- a/docs/v6/developer/customization/permissions.mdx+++ /dev/null@@ -1,70 +0,0 @@-----title: Permissions-description: The permission catalog, staff roles, and how extensions register their own permissions.------Staff roles and their permissions are managed as data — in the dashboard under **Settings → Roles**, through the Admin API (`/api/v3/admin/roles`), or in seeds. There is nothing to configure in Ruby for day-to-day permission management. This page covers what extension and host-application developers can plug into.--## The permission catalog--Every grantable capability is a flat key of the form `read_<resource>` or `write_<resource>` — the same vocabulary secret API keys use as scopes. `write_*` implies the matching `read_*`. Discover the catalog at runtime with `GET /api/v3/admin/permissions`; the role editor and the API-key scope picker are both rendered from it.--Keys are per resource, not per action. The money-adjacent areas (`payments`, `refunds`, `gift_cards`, `store_credits`) are separate resources from `orders`, so "view orders but don't refund" needs no special casing.--Roles as code is plain ActiveRecord:--```ruby-# db/seeds.rb-Spree::Role.find_or_create_by!(name: 'support')- .update!(permissions: %w[read_orders read_customers], description: 'Read-only support')-```--A role with `mutable: false` (set from seeds or the console) renders read-only in the dashboard — for roles the application does not want store staff to edit. The `admin` role is always protected.--## Registering extension permissions--Register your models as a catalog resource once; the keys appear in the role editor and become mintable API-key scopes with no further wiring:--```ruby-# in your engine's initializer-Spree.permissions.register_resource(:reviews, group: :catalog, subjects: -> {- [SpreeReviews::Review]-})-```--- `group` places the row in the permission pickers (`:orders`, `:catalog`, `:marketing`, `:customers`, `:settings`, `:access`, `:analytics` — or your own).-- `subjects` is a lambda returning the CanCanCan subjects the keys grant; it resolves lazily, so load order does not matter.-- Pass `write: false` for read-only resources.--Localize the labels in your engine's locale file under `spree.permissions_catalog.resources.<name>` (`label` and `description`), and declare the same resource on your admin controllers with `scoped_resource :reviews`.--## Beyond the catalog--The catalog is deliberately flat: it answers "may this role touch this kind of record", and that is the whole grant vocabulary. Two rules that do *not* belong in it:--- **Record-state rules** ("a completed order cannot be deleted") live on models and workflows, so they bind every caller — including secret API keys, which never consult CanCanCan.-- **Row-level restrictions** (a support agent limited to one market) are not expressible as keys. Replace the ability class outright:--```ruby-# config/initializers/spree.rb-Spree::Dependencies.ability_class = 'MyApp::Ability'-```--```ruby-# app/models/my_app/ability.rb-class MyApp::Ability < Spree::Ability- def initialize(user, options = {})- super- return unless user.respond_to?(:market_id) && user.market_id-- cannot :manage, Spree::Order- can [:read, :admin], Spree::Order, market_id: user.market_id- end-end-```--## How enforcement works--Every Admin API controller declares its resource (`scoped_resource :orders`). Each request checks the principal's keys — a staff member's role permissions on the current store, or a secret key's scopes — against `read_<resource>` or `write_<resource>` for the action. A missing key produces a 403 naming it in `details.required_permission`. Behind that gate, keys compile to CanCanCan rules for record-level concerns, and `GET /api/v3/admin/me` returns both the rule dump the dashboard mirrors and `permission_keys`, the flat key list.--Storefront customers are not part of this system — customer authorization is ownership, enforced by the Store API's scoped lookups, with nothing to configure. The one swappable piece is `Spree::Storefront::AccessPolicy` (via `Spree::Dependencies.storefront_access_policy_class`): a generic `readable?` / `writable?` / `scope` protocol that defaults to "the caller owns the record", with carts and orders adding guest-token access. Replace it only when access must widen beyond the owner, such as company accounts sharing purchases or wishlists.diff --git a/docs/v6/developer/customization/quickstart.mdx b/docs/v6/developer/customization/quickstart.mdxdeleted file mode 100644index 9668b1a215..0000000000--- a/docs/v6/developer/customization/quickstart.mdx+++ /dev/null@@ -1,251 +0,0 @@-----title: Quickstart-og:title: Spree Customization Quickstart-description: Recommended ways to customize the Spree 6 backend — configuration, workflow hooks, events, checkout steps, providers, dependencies, and decorators as a last resort.------Spree is designed to be customized without forking it. This guide presents the options **in order of recommendation** — start at the top and only move down when a simpler option doesn't fit.--<Note>-Business logic is extended through **workflow hooks** rather than by replacing classes wholesale, and the admin is a React application with its own extension points rather than a Rails engine extended through partials.-</Note>--## Quick reference--| What you want to do | Recommended approach |-|---|---|-| Change store settings (currency, markets, languages) | [Store settings](#store-settings) |-| Tweak Spree behavior globally | [Configuration](#configuration) |-| Run your own logic inside checkout, cancellation, refunds | [Workflow hooks](#workflow-hooks) |-| Block an operation from happening | [Workflow hooks](#workflow-hooks) — `validate` |-| React after something happened (sync, notifications) | [Events & subscribers](#events-and-subscribers) |-| Add or reorder checkout steps | [Checkout registry](#checkout-steps) |-| Swap tax, delivery rate, search or fulfillment behavior | [Providers](#providers) |-| Add searchable/filterable fields | [Search & filtering](#search-and-filtering) |-| Use your own user model or identity provider | [Authentication](#authentication) |-| Notify external services | [Webhooks](#webhooks) |-| Replace a whole workflow or service | [Dependencies](#dependencies) |-| Add associations/validations to models | [Decorators](#decorators) (last resort) |--<Info>-**Customizing the admin?** This page covers the backend — models, API and business logic. The Spree 6 admin is a separate React application with its own extension points. See [Dashboard Customization](/developer/dashboard/customization/quickstart).-</Info>--<AccordionGroup>- <Accordion title="Store settings" defaultOpen>- **Best for:** currency, markets, delivery zones, languages, and other business settings.-- Most day-to-day configuration is data, not code. Change it in the dashboard under **Settings** — no deploy required.- </Accordion>- <Accordion title="Configuration">- **Best for:** tweaking Spree's behavior globally.-- ```ruby config/initializers/spree.rb- Spree.config do |config|- config.minimum_password_length = 10- end- ```-- See [Configuration](/v6/developer/customization/configuration).- </Accordion>- <Accordion title="Workflow hooks">- **Best for:** running your own logic *inside* a core flow — checkout completion, order cancellation, refunds, fulfillment creation.-- <Info>- Hooks are the **headline extension point in Spree 6**. Before them, customizing a flow meant replacing the entire class and keeping your copy in sync with core forever.- </Info>-- Register a handler against a hook key — `<workflow key>.<hook name>`:-- ```ruby config/initializers/spree.rb- Spree.hooks.register('carts.complete.validate') do |flow|- flow.reject!('We cannot deliver to this region') unless deliverable?(flow.cart)- end- ```-- Pass a class instead of a block for anything longer than a line:-- ```ruby- Spree.hooks.register('carts.complete.after_finalize', 'MyApp::PushOrderToERP')- ```-- There are three families of hook:-- | Family | Naming | What it can do |- |---|---|---|- | **validate** | `validate` | Veto the operation with `flow.reject!(message)` |- | **lifecycle** | past tense — `after_finalize`, `after_cancel` | React to what happened; read-only |- | **context** | `set_*_context`, `get_provider_data` | Return a hash that gets merged into the flow's data |-- Hook keys are validated after boot, so a typo fails startup rather than silently never running.-- See [Services & Workflows](/developer/customization/workflows) for the full list of flows and their hooks.- </Accordion>- <Accordion title="Events and subscribers">- **Best for:** reacting *after* something happened — syncing to external systems, notifications, audit logging.-- ```ruby app/subscribers/spree/order_placed_subscriber.rb- module Spree- class OrderPlacedSubscriber < Spree::Subscriber- subscribes_to 'order.placed'-- def handle(event)- order = Spree::Order.find_by_prefix_id(event.payload['id'])- return unless order-- MyApp::ERP.push(order)- end- end- end- ```-- **Events or hooks?** A hook runs *inside* the flow and can influence or block it. An event fires *after* the fact and cannot. Reach for an event unless you need to change the outcome.-- See [Events](/developer/core-concepts/events).- </Accordion>- <Accordion title="Checkout steps">- **Best for:** adding, removing or reordering checkout steps.-- Spree 6 has no checkout state machine. A cart reports what it still needs, and you can add to that list:-- ```ruby config/initializers/spree.rb- Spree::Checkout::Registry.register_step(- name: :loyalty,- before: :payment,- satisfied: ->(cart) { cart.metadata['loyalty_number'].present? },- requirements: ->(cart) {- [{ step: 'loyalty', field: 'loyalty_number', message: 'Loyalty number is required' }]- }- )- ```-- Or attach a requirement to an existing step:-- ```ruby- Spree::Checkout::Registry.add_requirement(- step: :payment,- field: :po_number,- message: 'PO number is required',- satisfied: ->(cart) { cart.metadata['po_number'].present? }- )- ```-- Registered requirements appear in the Cart API's `requirements` array, so your storefront renders them without duplicating any rules.-- See [Carts](/v6/developer/core-concepts/carts#checkout-requirements).- </Accordion>- <Accordion title="Providers">- **Best for:** swapping a whole area of behavior for your own implementation.-- Spree 6 exposes pluggable providers for the domains that vary most between businesses:-- | Provider | Controls |- |---|---|- | Tax provider | How tax is calculated, per market |- | Delivery rate provider | How delivery is priced — flat rates or live carrier rates |- | Fulfillment provider | How a delivery type behaves — shipping, digital, pickup |- | Search provider | Database or Meilisearch |- | Payout provider | Where marketplace payouts go |-- Each is a class you register and select on the relevant record, so no conditional code lands in core.-- See [Fulfillments](/v6/developer/core-concepts/fulfillments#delivery-types) and [Taxes](/developer/core-concepts/taxes).- </Accordion>- <Accordion title="Search and filtering">- **Best for:** making custom fields searchable and sortable in the dashboard and API.-- ```ruby config/initializers/spree.rb- Spree.ransack.add_attribute(Spree::Product, :erp_id)- Spree.ransack.add_association(Spree::Product, :brand)- Spree.ransack.add_scope(Spree::Product, :featured)- ```-- See [Search & Filtering](/developer/core-concepts/search-filtering).- </Accordion>- <Accordion title="Authentication">- **Best for:** using your own user model or identity provider.-- Spree 6 owns its authentication stack rather than depending on Devise, and separates the customer identity from the staff identity. Point Spree at your own classes with `Spree.user_class` and `Spree.admin_user_class`.-- See [Authentication](/developer/customization/authentication).- </Accordion>- <Accordion title="Webhooks">- **Best for:** notifying external services — ERPs, CRMs, fulfillment systems — without writing Ruby.-- Configure them in the dashboard under **Settings → Webhooks**, or through the Admin API.-- See [Webhooks](/developer/core-concepts/webhooks).- </Accordion>- <Accordion title="Dependencies">- **Best for:** replacing an entire workflow or service with your own class.-- ```ruby config/initializers/spree.rb- Spree::Dependencies.cart_add_item_workflow = 'MyApp::Carts::AddItem'- ```-- <Warning>- Seam names end in `_workflow` in Spree 6. The old `*_service` names still resolve for one release with a warning, but **writes to them are ignored** — a class written against the old service contract isn't interchangeable with a workflow. Update the key when you upgrade.- </Warning>-- Prefer a hook when you only need to add behavior. Replace the class only when you need to change what the flow fundamentally does.-- See [Dependencies](/v6/developer/customization/dependencies).- </Accordion>- <Accordion title="Decorators">- **Best for:** adding associations, validations and scopes to Spree models. Use as a last resort.-- <Warning>- Decorators couple your code to Spree internals and are the most common cause of painful upgrades.-- **Do not use decorators for:**- - Logic inside a core flow → use [workflow hooks](#workflow-hooks)- - After-save callbacks → use [events](#events-and-subscribers)- - External service sync → use [webhooks](#webhooks)- - Replacing a service → use [dependencies](#dependencies)- - Admin UI changes → use [dashboard customization](/developer/dashboard/customization/quickstart)- </Warning>-- They remain appropriate for structural additions:-- ```ruby app/models/spree/product_decorator.rb- module Spree- module ProductDecorator- def self.prepended(base)- base.belongs_to :brand, class_name: 'MyApp::Brand', optional: true- base.scope :featured, -> { where(featured: true) }- end-- def full_title- "#{brand&.name} #{name}"- end- end-- Product.prepend(ProductDecorator)- end- ```-- See [Decorators](/developer/customization/decorators).- </Accordion>-</AccordionGroup>--## Choosing between hooks, events and dependencies--These three overlap, and picking the wrong one is the most common source of upgrade pain:--<Steps>- <Step title="Do you need to block or change the outcome?">- Use a **workflow hook**. Only `validate` hooks can stop an operation, and only they run early enough to do so safely — before money moves.- </Step>- <Step title="Do you just need to know it happened?">- Use an **event subscriber**. It's decoupled, testable, and survives upgrades untouched.- </Step>- <Step title="Do you need the flow to do something fundamentally different?">- Use **dependencies** to replace the class — and accept that you now own keeping it current.- </Step>-</Steps>--## Related--- [Services & Workflows](/developer/customization/workflows) — the workflow model and every hook-- [Carts](/v6/developer/core-concepts/carts) — checkout requirements and completion-- [Dashboard Customization](/developer/dashboard/customization/quickstart) — extending the admindiff --git a/docs/v6/user/returns/returns-processing.mdx b/docs/v6/user/returns/returns-processing.mdxdeleted file mode 100644index 7eaf62d1a0..0000000000--- a/docs/v6/user/returns/returns-processing.mdx+++ /dev/null@@ -1,87 +0,0 @@-----title: "Returns Processing"-description: "Learn how to process returns, exchanges, and claims in Spree Commerce."------Spree 6 handles everything that happens after a sale with three records, each covering a different situation:--- **Return** — the customer sends items back and gets their money back.-- **Exchange** — the customer sends items back and gets different items instead, such as another size or colour.-- **Claim** — something went wrong with the delivery. The item arrived damaged, never arrived, or was the wrong product. You can send a replacement, refund the customer, or both, without asking for the original item back.--Each one belongs directly to an order, so opening an order shows you everything that has happened to it.--<Note>- This replaces the older three-step flow of Return Authorization, Customer Return, and Reimbursement. One record now covers the whole operation from request through to refund.-</Note>--## Returns--### 1. Open the return--Find the order and create a return against it, choosing the items coming back and how many units of each. You can also record the reason for the return, which stock location the goods are returning to, and an internal memo.--Customers can also open returns themselves from their account, if your storefront offers it. Those arrive with the status **requested**.--### 2. Approve it--Approving a return tells the customer it is authorised.--<Note>- Spree does not generate prepaid return labels yet. That arrives with the carrier integrations, which is where the label actually comes from. Until then, most merchants send a label from their carrier's own tools and paste the link into the return's notes.-</Note>--### 3. Receive the goods--When the parcel arrives, record what actually turned up. Partial returns are normal, so you enter the quantity received for each line rather than assuming everything the customer said they would send has arrived.--You also mark each line as resellable or not. Resellable items go back into stock automatically at the return's stock location; damaged items do not.--### 4. Refund the customer--Refund the return to either the original payment method or store credit. You can refund the full amount or part of it, and you can refund in more than one step — part to store credit and part back to the card, for example.--Once the refund goes through, the customer receives an email confirming it.--<Note>- A return can be cancelled at any point before the goods are received. Cancelling restocks nothing.-</Note>--## Exchanges--An exchange follows the same path as a return — open, approve, receive — but instead of refunding the customer at the end, you fulfil the replacement items.--When you fulfil an exchange, Spree creates the replacement shipment for the quantities that were actually received, and checks the replacements are in stock first.--If the replacement items are worth less than what came back, the difference is returned to the customer as store credit or refunded to their original payment method. If the replacements are worth more, Spree records the difference but does not charge the customer automatically — collecting that balance is up to you, so nobody's card is charged without them agreeing to it.--## Claims--A claim starts when a customer reports a problem. Claims record what went wrong — damaged, missing, wrong item, or another reason you define — and the customer can attach photographs as evidence.--When you resolve a claim you choose what to do:--- **Refund** — money back, with no items required in return.-- **Replacement** — ship the item again, either the same variant or a different one.-- **Refund and replacement** — both.--You can also deny a claim if it does not hold up, or cancel it.--## Where to find them--Returns, exchanges, and claims each have their own section in the dashboard, so you can see everything in progress across all orders. Individual records also appear on the order they belong to, giving you the full history of that order in one place.--## Reasons--Spree keeps two separate lists of reasons, managed under **Settings → Returns & reasons** and seeded when your store is created:--- **Return reasons** explain why a customer is sending something back — "wrong size", "changed my mind", "no longer needed". These apply to both returns and exchanges.-- **Claim reasons** explain what went wrong on your end — "arrived damaged", "never arrived", "wrong item sent".--They are kept separate because they answer different questions, and mixing them makes reporting less useful. See [Settings → Returns Configuration](/v6/user/settings/returns-configuration) for how to manage them.--## Return policy--Spree does not enforce a return window, restocking fee, or final-sale rule out of the box. Every merchant's policy differs, and the rules often vary by country for legal reasons.--Instead, your developers can attach your policy to the point where a return is created. A common setup enforces the policy for customers opening returns themselves, while still letting your staff override it — so a supervisor can accept a return outside the window for a good customer without needing a code change.diff --git a/docs/v6/user/settings/returns-configuration.mdx b/docs/v6/user/settings/returns-configuration.mdxdeleted file mode 100644index 29ba35a148..0000000000--- a/docs/v6/user/settings/returns-configuration.mdx+++ /dev/null@@ -1,59 +0,0 @@-----title: "Returns Configuration"-description: "Learn how to define return reasons, claim reasons, and refund reasons."------Returns management is a crucial part of ecommerce operations. It builds customer trust, streamlines support workflows, and helps maintain clarity around inventory and financial adjustments.--Not all ecommerce platforms offer built-in tools for managing returns, but fortunately Spree does — no extra plugins or custom development needed.--Before you start processing returns, it is worth setting up the three lists of reasons Spree uses. Each answers a different question, which is why they are kept apart: mixing them together makes your reporting far less useful.--## Return Reasons--Return reasons record why a customer is sending something back. They apply to both returns and exchanges.--Typical examples are "Wrong size", "No longer needed", "Different from description", and "Arrived too late".--Each reason has two fields:--- **Name**: the reason itself, as your team and customers will see it.-- **Status**: whether the reason is available for use. Setting a reason to inactive hides it from new returns without deleting the history of returns that already used it.--## Claim Reasons--Claim reasons record what went wrong with a delivery — problems on your end rather than a customer changing their mind.--Typical examples are "Arrived damaged", "Never arrived", "Wrong item sent", and "Missing item from order".--They have the same two fields as return reasons: a name and a status.--<Note>- Claims also have a separate **type** field — damaged, missing, wrong item, or other — which is a broader grouping than the reason. Your developers can add more types if the standard four do not fit your business.-</Note>--## Refund Reasons--Refund reasons explain why money was sent back. They are used internally for tracking, reporting, and communication across teams, and they apply to any refund, whether or not a return was involved.--Typical examples are "Return processing" and "Order cancelled".--## Managing reasons--All three lists live together under **Settings → Returns & reasons**. Spree seeds a starting set when your store is created, so returns, claims, and refunds work out of the box, and you can add, rename, deactivate, or delete entries from there.--Each reason has two fields: its **name**, and whether it is **available on new records**. Turning that switch off retires a reason — it stops appearing when staff open a new return, claim, or refund, while every record that already used it keeps its explanation.--A reason that is already attached to a record cannot be deleted, because the records that used it would lose their explanation. Those reasons are marked **In use**. Deactivate one instead to retire it, and rename it at any time — every record pointing at it follows the new name.--## What about return windows and restocking fees?--Spree does not ship with a fixed return window, restocking fee, or final-sale setting. Return policy varies enormously between merchants, and often has to differ by country for legal reasons — the European Union, for example, requires a minimum withdrawal period that many other markets do not.--Rather than guessing, Spree gives your developers a place to attach your own policy when a return is created. A common arrangement enforces the policy for customers opening returns themselves, while letting your staff override it, so a supervisor can accept a late return for a loyal customer without needing any code changes.--## Processing Returns--Once your reasons are set up, you are ready to handle returns, exchanges, and claims.--To learn how, see [Returns → Returns Processing](/v6/user/returns/returns-processing).