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
Update Developer Docs Core Concepts for Spree 6
Damian Legawiec6f75857ba5a1
diff --git a/docs/developer/core-concepts/addresses.mdx b/docs/developer/core-concepts/addresses.mdxindex 61c728f942..34f19e5dc6 100644--- a/docs/developer/core-concepts/addresses.mdx+++ b/docs/developer/core-concepts/addresses.mdx@@ -1,289 +1,194 @@---title: Addresses-description: How Spree models addresses, countries, states, and zones, and how geographic data drives checkout, tax calculation, and shipping rates.+description: How Spree handles addresses, country and state data, and building address forms that adapt to the country a customer picks.---## 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+An address is where something goes or who gets billed. Every cart collects a shipping and a billing address, and signed-in customers can keep an address book.++Addresses matter beyond the label on a parcel: the shipping address decides which delivery options a customer sees and how much tax they pay.++```mermaid+erDiagram+ Customer ||--o{ Address : "address book"+ Cart }o--|| Address : "shipping"+ Cart }o--|| Address : "billing"+ Order }o--|| Address : "shipping (copied)"+ Order }o--|| Address : "billing (copied)"++ Address {+ string first_name+ string last_name+ string address1+ string city+ string postal_code+ string country_code+ string state_code+ }```-- [**Markets**](/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.+## Address fields| Field | Description |-|-------|-------------|+|---|---|| `first_name`, `last_name` | Contact name || `address1`, `address2` | Street address || `city` | City |-| `postal_code` | Postal code (not required for all countries) |+| `postal_code` | Postal code — not used by every country || `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`) |+| `company` | Company name, optional |+| `country_code` | Country, as an ISO code such as `US` |+| `state_code` | State or province code such as `CA`, where the country has them |+| `state_name` | Free text, for countries with no official list |+| `label` | What the customer filed it under — "Home", "Office" |+| `is_default_shipping`, `is_default_billing` | Whether it is the default in the address book |++<Note>+Countries and states are named by their **ISO codes** — `country_code: "US"`, `state_code: "CA"` — never by an ID. A code means the same thing everywhere, so you can send one without looking anything up first.++The older names `country_iso` and `state_abbr` still work but are going away. Use `country_code` and `state_code` in new code.+</Note>-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.+## Address forms that adapt-### Customer Address Book+Address formats are not universal. The United States wants a state and a ZIP code; Hong Kong wants neither. A form that demands both everywhere will block real customers from checking out.-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.+Every country tells you what it needs:++<CodeGroup>++```typescript Store SDK+const { data: countries } = await client.countries.list()++// One country, with its states for a picker+const usa = await client.countries.get('US', { expand: ['states'] })++usa.states_required // true → show a state picker+usa.zipcode_required // true → require a postal code+usa.states // [{ abbr: "CA", name: "California" }, ...]+```++```bash cURL+curl 'https://api.mystore.com/api/v3/store/countries' \+ -H 'X-Spree-API-Key: pk_xxx'++curl 'https://api.mystore.com/api/v3/store/countries/US?expand=states' \+ -H 'X-Spree-API-Key: pk_xxx'+```++</CodeGroup>++Drive the form from those two flags rather than hardcoding a list of countries. When `states_required` is `false`, let the customer type a `state_name` instead of picking a `state_code`.++Only countries you actually sell to are listed — that's decided by your [Markets](/developer/core-concepts/markets).++## The customer address book++A signed-in customer can save addresses and mark defaults, so checkout is one tap next time.<CodeGroup>```typescript Store SDK-// List addressesconst { data: addresses } = await client.customer.addresses.list()-// Create an addressconst address = await client.customer.addresses.create({+ label: 'Home',first_name: 'John',last_name: 'Doe',address1: '123 Main St',city: 'Los Angeles',- country_iso: 'US',- state_abbr: 'CA',+ country_code: 'US',+ state_code: 'CA',postal_code: '90001',phone: '555-0100',+ is_default_shipping: true,})-// 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 })+await client.customer.addresses.update(address.id, { city: 'Brooklyn' })+await client.customer.addresses.delete(address.id)``````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 addresscurl -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 'Authorization: Bearer <customer_token>' \-H 'Content-Type: application/json' \-d '{+ "label": "Home","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"+ "country_code": "US",+ "state_code": "CA",+ "postal_code": "90001"}'--# 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+## Addresses at checkout-During checkout, you can either reference a saved address by ID or pass a new address inline. See the [cart and checkout SDK guide](/developer/sdk/store/cart-checkout) for the full flow of passing addresses during checkout:--<CodeGroup>+On a cart you can point at a saved address or send a new one inline:```typescript Store SDK-// Use saved addresses+// Reuse something from the address bookawait client.carts.update(cartId, {shipping_address_id: 'addr_xxx',billing_address_id: 'addr_yyy',})-// Or pass new addresses inline+// Or send one directly — nothing needs saving firstawait 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',+ country_code: 'US',+ state_code: '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](/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](/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](/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-- **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](/developer/core-concepts/taxes))-2. Which **shipping methods** are available (see [Shipments](/developer/core-concepts/fulfillments))+Setting the shipping address is what makes delivery options and tax appear, so do it before asking the customer to choose delivery. The updated cart comes back with new totals — you don't need a second request.-Zones are configured in the admin dashboard — storefront developers don't interact with them directly via the API.+<Warning>+An address is **copied onto the order** when the cart completes, not linked to. Editing a saved address next year does not rewrite last year's invoice — which is exactly what you want when a customer moves house.+</Warning>-### Tax Zones and Markets+## Validating addresses-Each [Market](/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.+Spree checks that required fields are present and that the state and postal code make sense for the country. Anything it rejects comes back as a `422` naming the field, so you can put the message next to the input.-## How It All Fits Together+For real-world verification — that a street exists, that a unit number is missing — connect an address validation service. See [Providers](/developer/providers/overview).-Here's how geography flows through a typical checkout:+## How geography flows through a purchase-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+<Steps>+ <Step title="A customer arrives">+ Their country resolves to a [Market](/developer/core-concepts/markets), which sets the currency and locale, and whether prices are shown with tax included.+ </Step>+ <Step title="They fill in an address">+ The form adapts to the country using `states_required` and `zipcode_required`.+ </Step>+ <Step title="Delivery options appear">+ The shipping address decides which [delivery methods](/developer/core-concepts/fulfillments) can reach them, and what each costs.+ </Step>+ <Step title="Tax is worked out">+ The same address decides the [tax](/developer/core-concepts/taxes) charged.+ </Step>+ <Step title="The order is placed">+ Both addresses are copied onto the order as a permanent record.+ </Step>+</Steps>-## Related Documentation+## Related-- [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/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)+- [Markets](/developer/core-concepts/markets) — where you sell, in which currency+- [Fulfillments](/developer/core-concepts/fulfillments) — how the address shapes delivery options+- [Taxes](/developer/core-concepts/taxes) — how the address shapes tax+- [Carts](/developer/core-concepts/carts) — the checkout flow end to enddiff --git a/docs/developer/core-concepts/architecture.mdx b/docs/developer/core-concepts/architecture.mdxindex 1662fa4f3d..06c135c5c6 100644--- a/docs/developer/core-concepts/architecture.mdx+++ b/docs/developer/core-concepts/architecture.mdx@@ -1,180 +1,168 @@---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.+description: How Spree fits together — the catalog, the cart, the order, and fulfillment — and the two APIs you build against.---## 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.+Spree is a commerce engine you drive through a REST API. It holds the catalog, works out what a customer owes, takes the money, and tracks what was sent. You build the storefront, the mobile app, or the internal tool on top of it.-<Info>- Spree supports PostgreSQL, MySQL, and SQLite. PostgreSQL is recommended for production. [Learn more about database configuration](/developer/deployment/database).-</Info>+There is no built-in storefront you have to accept. Everything a customer-facing app needs is on the Store API, and everything a back office needs is on the Admin API. Both ship as typed TypeScript clients.++## The shape of a purchase-## Core Commerce Flow+Four things carry a purchase from browsing to delivery. Each one has a job the others don't:-The following diagram shows how the main models interact during a typical customer purchase:+<CardGroup cols={2}>+ <Card title="Product" icon="package" href="/developer/core-concepts/products">+ What you sell. A product has variants — the actual buyable items, each with its own price and stock.+ </Card>+ <Card title="Cart" icon="shopping-cart" href="/developer/core-concepts/carts">+ What a customer is assembling. It changes constantly and is usually abandoned.+ </Card>+ <Card title="Order" icon="receipt" href="/developer/core-concepts/orders">+ What they committed to. A permanent financial record that must not change quietly.+ </Card>+ <Card title="Fulfillment" icon="truck" href="/developer/core-concepts/fulfillments">+ What actually ships. One parcel, from one location, with one tracking number.+ </Card>+</CardGroup>```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+flowchart LR+ Product --> Variant+ Variant --> Cart+ Cart -->|complete| Order+ Order --> Fulfillment+ Order --> Payment++ style Cart fill:#e3f2fd,stroke:#0077ff+ style Order fill:#e8f5e9,stroke:#2e7d32```-**How it works:**--1. **Catalog** — [Products](/developer/core-concepts/products) have [Variants](/developer/core-concepts/products#variants) (SKUs) with prices and inventory tracked at [Stock Locations](/developer/core-concepts/inventory#stock-locations)--2. **Shopping** — Customers add Variants to their cart, creating an [Order](/developer/core-concepts/orders) with Line Items+**A cart and an order are separate records**, and that distinction shapes most of the API. A cart tolerates half-finished states — no address yet, no payment chosen. An order has to keep saying what the customer actually agreed to pay, so once it exists, today's prices and promotions can't quietly rewrite it. Completing a cart creates the order.-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/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/taxes-discounts-fees) that modify order totals--## Core Model Relationships--This diagram shows the key database relationships between Spree's main models:+## How the pieces relate```mermaiderDiagram- Store ||--o{ Order : "has many"- Store ||--o{ Product : "has many"+ Store ||--o{ Product : "sells"+ Store ||--o{ Order : "records"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"+ Product }o--o{ Category : "filed under"+ Product }o--|| DeliveryProfile : "ships by"- 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"+ Variant ||--o{ Price : "priced in each currency"+ Variant ||--o{ StockLevel : "stocked at locations"+ StockLevel }o--|| StockLocation : "held at"- Shipment ||--o{ InventoryUnit : "has many"- Shipment }o--|| StockLocation : "ships from"- Shipment }o--|| ShippingMethod : "via"+ Cart ||--o{ LineItem : "has many"+ Cart ||--o| Order : "completes into"+ LineItem }o--|| Variant : "of"+ Order ||--o{ LineItem : "has many"+ Order ||--o{ Fulfillment : "shipped as"+ Order ||--o{ Payment : "paid by"+ Order ||--o{ TaxLine : "taxed by"+ Order ||--o{ Discount : "reduced by"+ Order ||--o{ Fee : "surcharged by"+ Order }o--|| Customer : "placed by"++ Fulfillment }o--|| DeliveryMethod : "via"+ Fulfillment }o--|| StockLocation : "ships from"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+Three things in that diagram are worth calling out, because they're where Spree differs from what you might expect:++**Money added or removed is never one mixed list.** Tax, discounts and fees are three separate kinds of row. "What tax did we charge?" is a direct question with a direct answer instead of a filter over a mixed pile. See [Order totals](/developer/core-concepts/order-totals).-Spree exposes two REST APIs:+**Delivery is described by a profile, not a category.** A [delivery profile](/developer/core-concepts/fulfillments) says how a product travels — physically shipped, or digital — and which locations and methods serve it.-| 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 |+**Stock lives per location.** A variant has a stock level at each [stock location](/developer/core-concepts/inventory), so availability is a real question about real warehouses rather than a single number.-Both APIs share the same list shapes, filtering, querying, and pagination, and offer fully typed TypeScript clients — [@spree/sdk](/developer/sdk/quickstart) for the Store API and [@spree/admin-sdk](/developer/sdk/admin/quickstart) for the Admin API.+## The two APIs-Events from both APIs can trigger [Webhooks](/developer/core-concepts/webhooks) to notify external systems in real time.+```mermaid+flowchart TB+ Storefront["Storefront / mobile app"] -->|"@spree/sdk"| StoreAPI["Store API"]+ BackOffice["Dashboard / integrations"] -->|"@spree/admin-sdk"| AdminAPI["Admin API"]+ StoreAPI --> Spree[(Spree)]+ AdminAPI --> Spree+ Spree --> Webhooks["Webhooks & events"]+ Webhooks --> External["Your systems"]+```-## Multi-Store Architecture+| API | For | Authentication |+|---|---|---|+| [**Store API**](/api-reference/store-api/introduction) | Anything a customer touches — browsing, cart, checkout, their account | [Publishable key](/api-reference/store-api/authentication), plus a customer token once signed in |+| [**Admin API**](/api-reference/admin-api/introduction) | Anything staff or systems touch — catalog, orders, settings | [Secret key](/api-reference/admin-api/authentication) with scopes, or a staff token |-Spree supports running [multiple storefronts](/developer/multi-tenant/quickstart) from a single installation. Each Store can have:+The split is about exposure, not convenience. A publishable key is safe in browser code because it can only reach what a shopper is allowed to see. A secret key never belongs in a browser.-- Its own domain and branding-- Different currencies and locales-- Separate product catalogs-- Independent payment and shipping methods-- Isolated orders and customers+Both APIs share the same filtering, pagination and error shapes, so what you learn on one carries to the other. Both return **prefixed IDs** — `prod_86Rf07xd4z`, `cart_k5nR8xLq` — so an ID tells you what it points at.-This makes Spree suitable for multi-brand retailers, international expansion, or B2B/B2C hybrid setups.+<Note>+Money is always a **string**: `"135.60"`, never `135.60`. JavaScript can't represent every decimal exactly — `0.1 + 0.2` gives `0.30000000000000004` — which is not something you want inside a price. Every amount also comes formatted for its currency as `display_total`, `display_price` and so on. Render the `display_` one.+</Note>-## Extension Points+## Building on top-Spree is designed to be customized without modifying core code. The main extension mechanisms are:+Spree assumes you'll extend it, and gives you three ways in that survive an upgrade:-| Mechanism | Use Case | Documentation |-|-----------|----------|---------------|-| **Events & Subscribers** | React to order completion, payment, shipment events | [Events Guide](/developer/core-concepts/events) |-| **Webhooks** | Notify external systems of changes | [Webhooks Guide](/developer/core-concepts/webhooks) |-| **Dependencies** | Swap out services (tax calculation, shipping estimation) | [Dependencies Guide](/developer/customization/dependencies) |-| **Decorators** | Modify existing core models & classes behavior (use sparingly) | [Decorators Guide](/developer/customization/decorators) |+| Approach | Use it for | Guide |+|---|---|---|+| **Webhooks** | Telling another system something happened — an ERP, a warehouse, an email tool | [Webhooks](/developer/core-concepts/webhooks) |+| **Custom fields** | Storing your own data on a product, order or customer without changing the schema | [Custom Fields](/developer/core-concepts/metafields) |+| **Providers** | Plugging in a real service for tax, delivery rates, payments or search | [Providers](/developer/providers/overview) |-<Info>-For most customizations, prefer **Events** and **Dependencies** over Decorators. They're easier to maintain and won't break during upgrades.-</Info>+For merchant-managed data, reach for [custom fields](/developer/core-concepts/metafields) before anything heavier — they're queryable and editable in the dashboard without touching code.-## Packages+## Multi-store, multi-market, multi-seller-Spree is distributed as a set of packages:+One Spree installation can run more than one business:-**Core (required):**+- **[Stores](/developer/core-concepts/stores)** are separate businesses — their own catalog, orders, customers and settings. Data does not cross between them.+- **[Channels](/developer/core-concepts/channels)** are the ways one store sells: a website, a mobile app, a retail till.+- **[Markets](/developer/core-concepts/markets)** are the regions a store sells into, each with its currency, locale and tax treatment.+- **[Sellers](/developer/core-concepts/products#seller-submissions)** let one store list goods from many vendors, for a marketplace.-| Package | Purpose |-|---------|---------|-| `spree` | Models, services, business logic, Store API, Admin API, and Webhooks |+## What you install-**Optional:**+| Package | What it is |+|---|---|+| `spree` | The engine — catalog, checkout, payments, both APIs |+| `spree_emails` | Transactional email, if you don't send your own |+| `spree_dashboard` | The back-office dashboard |-| Package | Purpose |-|---------|---------|-| `spree_admin` | Admin dashboard for managing your store |-| `spree_emails` | Transactional email templates (order confirmation, shipping, etc.) |+Providers for search, delivery rates, tax and payments install separately, so you only carry what you use.-**TypeScript packages:**+**TypeScript:**-| Package | Purpose |-|---------|---------|-| [`@spree/sdk`](/developer/sdk/quickstart) | TypeScript SDK for the Store API |-| [`@spree/admin-sdk`](/developer/sdk/admin/quickstart) | TypeScript SDK for the Admin API |-| [`@spree/cli`](/developer/cli/quickstart) | Command line interface for managing local environment and using the Admin API from the terminal |+| Package | What it is |+|---|---|+| [`@spree/sdk`](/developer/sdk/quickstart) | Store API client — for your storefront |+| [`@spree/admin-sdk`](/developer/sdk/admin/quickstart) | Admin API client — for back-office and integrations |+| [`@spree/cli`](/developer/cli/quickstart) | Command line for local setup and calling the Admin API |-## Related Documentation+<Info>+Spree runs on PostgreSQL, MySQL or SQLite. PostgreSQL is recommended for production — [database configuration](/developer/deployment/database).+</Info>-- [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/fulfillments) — Shipping and fulfillment-- [Customization Quickstart](/developer/customization/quickstart) — How to extend Spree+## Where to go next++<CardGroup cols={2}>+ <Card title="Quickstart" icon="rocket" href="/developer/getting-started/quickstart">+ Get an installation running.+ </Card>+ <Card title="Store SDK" icon="code" href="/developer/sdk/quickstart">+ Build a storefront against the Store API.+ </Card>+ <Card title="Products" icon="package" href="/developer/core-concepts/products">+ How the catalog is modelled.+ </Card>+ <Card title="Carts" icon="shopping-cart" href="/developer/core-concepts/carts">+ Cart, checkout, and what completion guarantees.+ </Card>+</CardGroup>diff --git a/docs/developer/core-concepts/calculators.mdx b/docs/developer/core-concepts/calculators.mdxindex 6f5c2188ed..76d2eef4d9 100644--- a/docs/developer/core-concepts/calculators.mdx+++ b/docs/developer/core-concepts/calculators.mdx@@ -1,304 +1,118 @@---title: Calculators+description: The small pieces of arithmetic behind delivery charges and promotion discounts — what each one does and how to choose between them.---## 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"-```+A calculator works out an amount. "Charge $5 per item." "Take 15% off." "Free over $50, otherwise $7."-**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/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+They exist because the rule and the number are different questions. A promotion decides *whether* a discount applies; a calculator decides *how much*. Keeping them apart means a merchant can change "10% off" to "$10 off" without touching the conditions that decide who qualifies.-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:+Two things use calculators:-```ruby-def self.description- # Human readable description of the calculator-end+- **[Delivery methods](/developer/core-concepts/fulfillments)** — what delivery costs+- **[Promotions](/developer/core-concepts/promotions)** — how big a discount is-def compute(object=nil)- # Returns the value after performing the required calculation-end-```+<Info>+Tax does **not** use calculators. Tax is worked out by a [tax provider](/developer/core-concepts/taxes), which can be Spree's own rate tables or an external service.+</Info>-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.+## Choosing a calculator-## Available Calculators+Each calculator takes a few settings — the amount, the percentage, the threshold. A merchant picks one and fills in the settings when setting up a delivery method or a promotion.-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.+### For delivery charges-### Default Tax+| Calculator | What it charges | Settings |+|---|---|---|+| **Flat rate** | The same amount every time | `amount`, `currency` |+| **Per item** | An amount for each item in the parcel | `amount`, `currency` |+| **Percent of item total** | A percentage of what's in the parcel | `flat_percent` |+| **Price sack** | One amount above a threshold, another below — the usual "free delivery over $50" | `minimal_amount`, `discount_amount`, `normal_amount` |+| **Flexi rate** | A charge for the first item, less for each one after | `first_item`, `additional_item`, `max_items` |+| **Digital delivery** | Nothing, for downloads | — |-For information about this calculator, please read the [Taxes](/developer/core-concepts/taxes) guide.+### For promotion discounts-### Flat Percent Per Item Total+| Calculator | What it takes off | Settings |+|---|---|---|+| **Flat rate** | A fixed amount | `amount`, `currency` |+| **Percent of item total** | A percentage of the order | `flat_percent` |+| **Percent on line item** | A percentage of one item | `percent` |+| **Flexi rate** | A sliding amount by quantity | `first_item`, `additional_item`, `max_items` |+| **Tiered percent** | A percentage that grows with order value | tiers |+| **Tiered flat rate** | A fixed amount that grows with order value | tiers |-This calculator has one preference: `flat_percent` and can be set like this:+## Worked examples-```ruby-calculator.preferred_flat_percent = 10-```+<AccordionGroup>+ <Accordion title="Free delivery over $50, otherwise $7">+ **Price sack**, with `minimal_amount: 50`, `discount_amount: 0`, `normal_amount: 7`.-This calculator takes an order and calculates an amount using this calculation:+ A $60 basket pays nothing. A $20 basket pays $7.+ </Accordion>+ <Accordion title="$3 to ship the first item, $1 for each extra">+ **Flexi rate**, with `first_item: 3`, `additional_item: 1`.-```ruby-[item total] x [flat percentage]-```+ Four items cost `$3 + (3 × $1)` = **$6**. Set `max_items` to stop charging beyond a point.+ </Accordion>+ <Accordion title="10% off the order">+ **Percent of item total**, with `flat_percent: 10`.-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`.+ A $31 order gets **$3.10** off.+ </Accordion>+ <Accordion title="Spend more, save more">+ **Tiered percent** — 5% over $100, 10% over $250, 15% over $500.-### Flat Rate+ The order total picks the tier. One promotion covers the whole ladder instead of three competing ones.+ </Accordion>+</AccordionGroup>-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"-```+## Setting one up-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.+Calculators are configured as part of the thing that uses them. The available calculators for each are discoverable, so a dashboard or a script can present the real list rather than a hardcoded one:-This calculator can take any object and will return simply the preferred amount.+<CodeGroup>-### Flexi Rate+```typescript Admin SDK+// What can price a delivery method?+const calculators = await adminClient.deliveryMethods.calculators()-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])+// Set up a delivery method with a flat rate+await adminClient.deliveryMethods.create({+ name: 'Standard shipping',+ delivery_zone_id: 'dz_xxx',+ calculator_type: 'Spree::Calculator::Shipping::FlatRate',+ calculator_attributes: {+ preferences: { amount: '7.00', currency: 'USD' },+ },+})```-* 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]+```bash CLI+spree api get /delivery_methods/calculators```-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:+</CodeGroup>-* `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+Each calculator declares which settings it takes, so a form can be built for it without knowing the calculator in advance — which is how the dashboard renders these.-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`.+<Warning>+A calculator with an `amount` also has a **currency**. If it doesn't match the order's currency, the calculator contributes nothing rather than converting. Set up one calculator per currency you sell in, or a promotion will silently do nothing for some customers.+</Warning>-## Creating a New Calculator+## Writing your own-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>)-```+When none of the built-in calculators expresses your pricing — dimensional weight, a contract rate card, a rule your finance team invented — you can add one. A calculator is a small class with a name and a method that returns an amount, registered so it appears alongside the built-in options.-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.+For delivery specifically, consider whether you want a calculator or a **delivery rate provider**. A calculator computes a number from what's in the parcel. A provider asks a carrier for real, live rates. If you want what UPS would actually charge today, that's a provider.-## Related Documentation+See [Custom promotions](/developer/how-to/custom-promotion) and [Providers](/developer/providers/overview).-- [Adjustments](/developer/core-concepts/taxes-discounts-fees) — the records calculators compute amounts for.-- [Dependencies](/developer/customization/dependencies) — swap out calculators via the Dependencies system.+## Related+- [Fulfillments](/developer/core-concepts/fulfillments) — delivery methods and rates+- [Promotions](/developer/core-concepts/promotions) — the rules that decide when a discount applies+- [Discounts](/developer/core-concepts/discounts) — the rows a promotion produces+- [Taxes](/developer/core-concepts/taxes) — worked out by providers, not calculatorsdiff --git a/docs/developer/core-concepts/carts.mdx b/docs/developer/core-concepts/carts.mdxindex 187b11ce30..bb90f77e56 100644--- a/docs/developer/core-concepts/carts.mdx+++ b/docs/developer/core-concepts/carts.mdx@@ -140,7 +140,7 @@ This is what lets you design your own checkout. Spree tells you what's missing;shipping_address: {first_name: 'John', last_name: 'Doe',address1: '123 Main St', city: 'Los Angeles',- country_code: 'US', state_abbr: 'CA', postal_code: '90001',+ country_code: 'US', state_code: 'CA', postal_code: '90001',},})```diff --git a/docs/developer/core-concepts/channels.mdx b/docs/developer/core-concepts/channels.mdxindex e965a8a261..30c9c97c68 100644--- a/docs/developer/core-concepts/channels.mdx+++ b/docs/developer/core-concepts/channels.mdx@@ -3,10 +3,6 @@ title: Channelsdescription: Per-store distribution surfaces — online storefront, POS, marketplace, wholesale — each with its own product catalog and order attribution.----import { Since } from '/snippets/since.mdx';--<Since version="5.5" />-## OverviewChannels segment a single [Store](/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.@@ -96,8 +92,6 @@ This attribution drives reporting (best-selling by channel, revenue per channel)### 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 |diff --git a/docs/developer/core-concepts/companies-and-catalogs.mdx b/docs/developer/core-concepts/companies-and-catalogs.mdxindex 15f072cc7c..3cf4b9318b 100644--- a/docs/developer/core-concepts/companies-and-catalogs.mdx+++ b/docs/developer/core-concepts/companies-and-catalogs.mdx@@ -54,7 +54,7 @@ Memberships stay always-active and always customer-backed: the pending state livCarts and orders carry a `company_id` pointing at any node — buying *for* a division means pointing at it. A buyer with exactly one membership resolves to it automatically; a buyer with several names the node on their cart (the `company_id` param on cart update, validated against their standing). The node is frozen onto the order at completion, like every other order attribute, so a placed order's tax treatment stays explainable no matter how the tree changes later.-Exemption certificates and the company's tax registration always resolve through `company.legal_entity` — see [Taxes, Discounts & Fees](/docs/developer/core-concepts/taxes-discounts-fees) for how they reach the tax provider.+Exemption certificates and the company's tax registration always resolve through `company.legal_entity` — see [Taxes](/developer/core-concepts/taxes) for how they reach the tax provider.## Catalogsdiff --git a/docs/developer/core-concepts/customers.mdx b/docs/developer/core-concepts/customers.mdxindex 24404c945b..8b0be73fb4 100644--- a/docs/developer/core-concepts/customers.mdx+++ b/docs/developer/core-concepts/customers.mdx@@ -3,8 +3,6 @@ title: Customersdescription: How Spree models customer accounts — registration, authentication, addresses, order history, store credits, and guest checkout behavior.----import { Since } from '/snippets/since.mdx';-## OverviewCustomers interact with your store through the Store API. They can register, log in, manage their profile, and view order history.@@ -205,8 +203,6 @@ On success, the user is automatically logged in and a JWT token is returned. The## 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: Subscribediff --git a/docs/developer/core-concepts/discounts.mdx b/docs/developer/core-concepts/discounts.mdxnew file mode 100644index 0000000000..199e3f0f5c--- /dev/null+++ b/docs/developer/core-concepts/discounts.mdx@@ -0,0 +1,139 @@+---+title: Discounts+description: The record of money taken off one order — where a discount comes from, and why it is spread across the items it applied to.+---++## Overview++A discount is one line on one order saying money came off, and why.++<Note>+**A discount is not a promotion.** A [promotion](/developer/core-concepts/promotions) is a *rule* — "20% off shoes in July" — that exists on its own, before anybody buys anything. A discount is the *result* on a particular order.++Think of the promotion as the sign in the shop window and the discount as the line on the receipt. One promotion produces thousands of discounts over its life.+</Note>++That separation is what lets an order stay truthful. The promotion can be edited, paused or deleted next month; the discount row on last month's order still says exactly what that customer was given.++It also means **not every discount has a promotion behind it.** When a support agent takes $10 off as a goodwill gesture, that's a discount with no campaign attached — which is what the `kind` field distinguishes.++```mermaid+erDiagram+ Promotion ||--o{ Discount : "produces many, over time"+ Order ||--o{ Discount : "has many"+ LineItem ||--o{ Discount : "reduced by"+ Fulfillment ||--o{ Discount : "reduced by"++ Promotion {+ string name+ string code+ datetime expires_at+ }+ Discount {+ string label+ string kind+ string code+ string value+ string amount+ }+```++| | [Promotion](/developer/core-concepts/promotions) | Discount |+|---|---|---|+| What it is | A campaign rule | A row on one order |+| Exists | Before any order | Only once money comes off |+| How many | One | One per order it applies to |+| Can change later | Yes — edit or end it | No — it's a financial record |+| Set up by | A merchant, in advance | Created automatically, or by staff |++## Discount attributes++| Attribute | Description |+|---|---|+| `label` | What the customer sees — `Summer Sale` |+| `kind` | `promotion` or `manual` |+| `code` | The coupon code used, if there was one |+| `value` / `value_type` | The rule behind it — `"10"` and `percent` |+| `amount` / `display_amount` | What actually came off, as a negative amount |+| `promotion_id` | The promotion responsible, for promotion discounts |+| `line_item_id` / `fulfillment_id` | What it reduced |++Note the difference between `value` and `amount`. `value` is the rule — "10 percent". `amount` is the money — "-$12.00". You need the rule to explain the discount and the amount to add up the order.++## Reading discounts on an order++Whatever produced them, the rows read the same way:++```typescript Store SDK+const cart = await client.carts.get(cartId)++cart.display_discount_total // "-$12.00"++cart.discounts.forEach((discount) => {+ discount.label // "Summer Sale"+ discount.kind // "promotion" or "manual"+ discount.code // "SUMMER20", when a code was used+ discount.display_amount // "-$12.00"+})+```++Applying a coupon code, and what decides whether it's accepted, belongs to [Promotions](/developer/core-concepts/promotions).++## Manual discounts++Sometimes there's no promotion — a price match, an apology for a late delivery. Staff can add a discount directly:++<CodeGroup>++```typescript Admin SDK+// 10% off one line item+await adminClient.orders.discounts.create('or_xxx', {+ label: 'Goodwill discount',+ value: '10',+ value_type: 'percent',+ line_item_id: 'li_xxx',+})++// A flat amount across the order+await adminClient.orders.discounts.create('or_xxx', {+ label: 'Price match',+ value: '15.00',+ value_type: 'flat',+})+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/admin/orders/or_xxx/discounts' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{ "label": "Goodwill discount", "value": "10", "value_type": "percent" }'+```++</CodeGroup>++<Warning>+Only **manual** discounts can be edited or deleted. Changing one that came from a promotion returns a `422`.++That row belongs to the promotion that created it. If staff could edit it, an order would start disagreeing with the promotion it claims to have used — and the reporting behind "how did the summer sale do" stops adding up.+</Warning>++## How a discount is spread++An order-level discount isn't kept as one lump sum. It's divided across the items it applied to, in proportion to what they cost.++This looks like an implementation detail until someone returns one item out of three. Then the question is: how much of that $30 discount belonged to the returned shirt? If the discount were one lump, you'd have to guess. Because it was spread at the time, the answer is already recorded, and the refund is right without anyone doing arithmetic on the phone.++The same reasoning applies to tax — the tax on a partially returned order follows the same split.++## Discounts on placed orders++Once an order exists, its discounts stop being regenerated. Editing a placed order re-applies the rows it already has rather than re-running today's promotions.++The alternative would mean an order quietly changing because a sale ended overnight — which is indefensible to a customer holding a confirmation email.++## Related++- [Promotions](/developer/core-concepts/promotions) — the rules that create most discounts+- [Order totals](/developer/core-concepts/order-totals) — how discounts roll into the total+- [Gift cards & store credit](/developer/core-concepts/store-credits-gift-cards) — payment, not discount+- [Returns](/developer/core-concepts/returns-exchanges-claims) — how a discount is unwound on a returndiff --git a/docs/developer/core-concepts/events.mdx b/docs/developer/core-concepts/events.mdxindex c1444dea6f..280ebdafba 100644--- a/docs/developer/core-concepts/events.mdx+++ b/docs/developer/core-concepts/events.mdx@@ -1,665 +1,153 @@---title: Events-description: Spree's event system — publish and subscribe to lifecycle events from orders, products, and users to trigger background jobs and integrations.+description: Reacting to things that happen in Spree — an order placed, a payment taken, stock running out — without modifying core code.----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:+Something happens in a store — an order is placed, a payment clears, a product sells out — and you want something else to happen: notify a warehouse, post to a channel, update a spreadsheet.-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.+Events are how you attach that behaviour without editing Spree. Spree announces what happened; your code decides what to do about it.```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+flowchart LR+ Action["Order is placed"] --> Event["order.placed"]+ Event --> Sub["Your subscriber<br/>(in-app)"]+ Event --> Hook["Webhook<br/>(external system)"]```-<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+There are two ways to listen, and which you want depends on where your code lives:-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-```+| | Use it when |+|---|---|+| **[Webhooks](/developer/core-concepts/webhooks)** | The thing reacting is a separate system — a Next.js app, an ERP, an automation tool |+| **Subscribers** | The reaction belongs inside the Spree application itself |-### From Anywhere+If you're building a headless storefront, **webhooks are almost certainly what you want**. Subscribers are for when you're running Spree as your own application and want to add behaviour to it.-Use `Spree::Events.publish` directly:+## What Spree announces-```ruby-Spree::Events.publish(- 'inventory.low_stock',- { variant_id: variant.id, quantity: variant.total_on_hand }-)-```+Most records announce their own lifecycle:-## Event Serializers+| Event | When |+|---|---|+| `<resource>.created` | A record is created |+| `<resource>.updated` | It changes |+| `<resource>.deleted` | It's removed |-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.+Those exist for orders, carts, products, variants, customers, payments, fulfillments, returns, media, price changes and more.-### How Serializers Work+On top of that, meaningful business moments get their own events:-When a model publishes an event, Spree looks for a V3 serializer class matching the model name:+| Event | Meaning |+|---|---|+| `order.placed` | A customer completed checkout |+| `order.paid` | Payment is settled in full |+| `order.canceled` | The order was cancelled |+| `order.shipped` / `order.delivered` | Everything has shipped / arrived |+| `payment.completed` / `payment.voided` | A payment succeeded / was released |+| `fulfillment.shipped` / `fulfillment.canceled` | A parcel went out / was stood down |+| `product.out_of_stock` / `product.back_in_stock` | Availability flipped |+| `return.received` / `return.refunded` | A return arrived / was refunded |+| `import.completed` / `export.completed` | Bulk work finished |-- `Spree::Order` → `Spree::Api::V3::OrderSerializer`-- `Spree::Product` → `Spree::Api::V3::ProductSerializer`-- `Spree::Payment` → `Spree::Api::V3::PaymentSerializer`+The distinction matters when choosing what to listen for. `order.updated` fires whenever anything about an order changes — including an admin editing a note. `order.placed` fires once, when a customer actually bought something. Sending a confirmation email on the wrong one is how customers receive nine copies.-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`).+## What an event carries-If no serializer is found, a minimal fallback payload is returned:+An event carries the record it's about, serialized:```json-{ "id": "prod_86Rf07xd4z", "created_at": "2025-01-15T10:00:00Z", "updated_at": "2025-01-15T10:30:00Z" }+{+ "id": "or_86Rf07xd4z",+ "number": "R123456789",+ "status": "placed",+ "payment_status": "paid",+ "total": "135.60",+ "email": "[email protected]"+}```-### 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):+IDs are the same prefixed IDs the API uses, so you can take an ID out of an event and fetch the full record without translating anything.-| 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) |+## Reacting in another system-### Payload Context+Point a webhook at your endpoint and subscribe it to the events you care about. That's covered fully in [Webhooks](/developer/core-concepts/webhooks) — including signature verification, which you should not skip.-Event serializers receive specific context parameters that control what data is included:+## Reacting inside Spree-- **`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](/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-```+A subscriber is a small class that names the events it wants and does something when one arrives.-```ruby config/initializers/spree.rb-Spree.api.order_serializer = 'MyApp::OrderSerializer'+```bash+bin/rails g spree:subscriber OrderPlaced order.placed```-<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+The generator writes the class, a test, and — the step that's easy to forget — registers it.-If you add a custom model that publishes events, create a V3 serializer:+```ruby app/subscribers/order_placed_subscriber.rb+class OrderPlacedSubscriber < Spree::Subscriber+ subscribes_to 'order.placed'-```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-```+ def handle(event)+ order = Spree::Order.find_by_prefix_id(event.payload['id'])+ return unless order-```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+ WarehouseClient.new.submit(order)endend```-Models without a matching serializer will use a minimal fallback payload containing only `id`, `created_at`, and `updated_at`.+A subscriber can listen to several events, or to a whole family:-## 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+```ruby+subscribes_to 'order.placed', 'order.canceled'+subscribes_to 'order.*'```-To remove a built-in subscriber:+Subscribers must be registered — they aren't discovered automatically, because a subscriber that starts running because of where its file sits is hard to reason about:```ruby config/initializers/spree.rbRails.application.config.after_initialize do- Spree.subscribers.delete(Spree::ExportSubscriber)+ Spree.subscribers << OrderPlacedSubscriberend```-## Synchronous vs Asynchronous+### Subscribers run in the background-By default, subscribers run asynchronously via a background job. This prevents slow subscriber code from blocking HTTP requests.+By default a subscriber runs as a background job, so a slow API call in your code doesn't slow down the customer's checkout — and a failure doesn't roll back their order.-For critical operations that must complete before the request finishes, use synchronous mode:+That's almost always what you want. If you genuinely need to run inside the same transaction, you can ask to:```ruby-class CriticalOrderHandler < Spree::Subscriber- subscribes_to 'order.completed', async: false-- def handle(event)- # This runs immediately, blocking the request- end-end+subscribes_to 'order.placed', async: false```<Warning>-Use synchronous subscribers sparingly. They can significantly slow down your application if the handler code is slow or makes external API calls.+A synchronous subscriber runs while the customer waits, and an exception in it can fail their checkout. Reserve it for work that must be atomic with the order, and keep it fast.</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+## Publishing your own events-Stub `Spree::Events.publish` to assert an event is published:+Anything in your own code can announce something, and subscribers and webhooks treat it like any built-in event:```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'+order.publish_event('order.flagged_for_review')```-### 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-```+Useful when your own domain has moments worth reacting to — a fraud check completing, an approval granted.-### Base Class Interface+## Guidance-The `Spree::Events::Adapters::Base` class defines the required interface:+**Listen for the specific event.** `order.placed` rather than `order.updated` with a status check.-| 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 |+**Assume events can arrive more than once.** A retry after a network blip can redeliver. Make handlers safe to run twice — check whether you've already acted before acting.-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+**Don't chain long sequences of subscribers.** When one event triggers a subscriber that triggers another, working out what happened after the fact becomes archaeology. Prefer one handler that does the sequence.-<Info>-See `Spree::Events::Adapters::ActiveSupportNotifications` for a complete reference implementation.-</Info>+**Keep failures contained.** A subscriber that raises shouldn't take down anything else. Handle your own errors and log them.-## Related Documentation+## Related-- [Events Tutorial](/developer/tutorial/events) - Hands-on, step-by-step walkthrough of building an event subscriber-- [Webhooks](/developer/core-concepts/webhooks) - HTTP callbacks for external integrations-- [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/core-concepts/carts) - Using events in checkout customization+- [Webhooks](/developer/core-concepts/webhooks) — reacting from outside Spree+- [Orders](/developer/core-concepts/orders) — the order lifecycle these events describe+- [Imports & Exports](/developer/core-concepts/imports-exports) — completion events for bulk workdiff --git a/docs/developer/core-concepts/fees.mdx b/docs/developer/core-concepts/fees.mdxnew file mode 100644index 0000000000..900e33a62d--- /dev/null+++ b/docs/developer/core-concepts/fees.mdx@@ -0,0 +1,152 @@+---+title: Fees+description: Surcharges added to an order — handling, gift wrap, cash on delivery — and customs duties on cross-border sales.+---++## Overview++A fee is money added to an order that isn't the price of a product and isn't tax. Gift wrapping. A handling charge. The surcharge for paying cash on delivery. An import duty on a parcel crossing a border.++Fees are their own kind of row, separate from [tax](/developer/core-concepts/taxes) and [discounts](/developer/core-concepts/discounts), so a merchant can answer "what did we charge in handling this quarter" without untangling a mixed list.++```mermaid+erDiagram+ Order ||--o{ Fee : "order-level"+ LineItem ||--o{ Fee : "per item"+ Fulfillment ||--o{ Fee : "per parcel"+ Fee ||--o{ TaxLine : "may be taxed"++ Fee {+ string label+ string kind+ string amount+ string metadata+ }+```++## Fee attributes++| Attribute | Description |+|---|---|+| `label` | What the customer sees — `Gift wrapping` |+| `kind` | What sort of charge it is — see below |+| `amount` / `display_amount` | The charge |+| `line_item_id` | Set when the fee is for one item |+| `fulfillment_id` | Set when the fee is for one parcel |++When neither ID is set, the fee applies to the whole order.++| `kind` | Typical use |+|---|---|+| `surcharge` | A general extra charge |+| `handling` | Packing and processing |+| `gift_wrap` | Gift wrapping |+| `cod` | Cash on delivery |+| `payment` | A payment method surcharge |+| `duty` | Customs duty — see [below](#customs-duties) |++The list is open — an extension can add its own kind.++<Note>+**Fees are always positive.** To take money off, create a [discount](/developer/core-concepts/discounts) instead. This isn't pedantry: when a refund is worked out later, it has to know whether a row was a charge or a credit, and a negative fee makes that ambiguous.+</Note>++## Adding a fee++<CodeGroup>++```typescript Admin SDK+// Gift wrapping on one item+await adminClient.orders.fees.create('or_xxx', {+ label: 'Gift wrapping',+ kind: 'gift_wrap',+ amount: '5.00',+ line_item_id: 'li_xxx',+})++// A handling charge on the whole order+await adminClient.orders.fees.create('or_xxx', {+ label: 'Handling',+ kind: 'handling',+ amount: '2.50',+})+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/admin/orders/or_xxx/fees' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{ "label": "Gift wrapping", "kind": "gift_wrap", "amount": "5.00" }'+```++</CodeGroup>++Fees are visible to the storefront on the cart and the order, so a customer sees what they're being charged before they pay:++```typescript Store SDK+const cart = await client.carts.get(cartId)++cart.fees.forEach((fee) => {+ fee.label // "Gift wrapping"+ fee.display_amount // "$5.00"+})++cart.display_fee_total // "$7.50"+```++## Fees and tax++Fees are **taxable by default** — a handling charge in a VAT country is itself subject to VAT, and Spree writes tax lines against the fee accordingly.++Customs duties are the exception, described next.++## Customs duties++When a parcel crosses a border, the destination country may charge import duty. Whether the customer pays that at checkout or gets a bill from the courier later is a commercial decision — and quoting it up front is what avoids parcels being refused at the door.++A duty is recorded as a fee with `kind: 'duty'`. Two things make it different from every other fee.++### Duties aren't taxed++A duty is an import charge levied by the destination country, not a sale that domestic tax applies to. Charging tax on top of it would invent tax the merchant never owed, so Spree leaves duties out of the taxable set. Where import VAT genuinely applies, whoever calculated the duty records that tax itself.++### Duties remember what they were calculated from++A duty fee keeps a copy of its inputs — the commodity code, the country of origin, the rate — in its `metadata`.++This matters more than it sounds. A product's classification can be corrected next month; a supplier can change. What the customer was actually charged must not move when that happens. The snapshot is the authoritative record, and a duty is never re-derived from today's catalogue.++## Customs classification++For any of this to work, the goods have to be described in the language customs authorities use. Three fields on each variant do that:++| Field | What it is | Example |+|---|---|---|+| `hs_code` | The Harmonized System commodity code — the international classification for what the item *is* | `6109.10` |+| `country_of_origin` | Where it was made, as an ISO country code — not where it ships from | `PT` |+| `customs_description` | A plain description for the declaration, when the product name isn't clear enough | `Cotton t-shirt` |++```typescript Admin SDK+await adminClient.products.variants.update('prod_xxx', 'var_xxx', {+ hs_code: '6109.10',+ country_of_origin: 'PT',+ customs_description: 'Cotton t-shirt',+})+```++<Warning>+`country_of_origin` is where the item was **manufactured**, not the warehouse it leaves from. Duty rates and trade agreements turn on origin, so getting this wrong produces the wrong charge — and can hold a parcel at the border.+</Warning>++These fields are editable per variant and in the bulk product editor. They're also what a carrier integration puts on the customs declaration for an international label — required for cross-border parcels, ignored for domestic ones.++<Info>+Spree records classification and charges duties; it does not itself estimate them. A landed-cost provider calculates the numbers and writes the duty fees. See [Providers](/developer/providers/overview).+</Info>++## Related++- [Taxes](/developer/core-concepts/taxes) — how tax is worked out+- [Discounts](/developer/core-concepts/discounts) — taking money off+- [Order totals](/developer/core-concepts/order-totals) — how fees roll into what a customer pays+- [Products](/developer/core-concepts/products) — variants and their attributesdiff --git a/docs/developer/core-concepts/imports-exports.mdx b/docs/developer/core-concepts/imports-exports.mdxindex 7bbc54dd0a..8c2b407aab 100644--- a/docs/developer/core-concepts/imports-exports.mdx+++ b/docs/developer/core-concepts/imports-exports.mdx@@ -1,741 +1,172 @@---title: Imports & Exports+description: Moving data in and out of Spree as CSV — bulk catalog updates, customer lists, and order extracts.---## Overview-Spree provides a comprehensive bulk data import and export system for managing large datasets. The system supports CSV file processing with configurable field mapping, asynchronous processing via background jobs, and real-time progress tracking in the admin interface.+Spreadsheets remain how most merchants think about bulk work. A supplier sends a price list as CSV; the finance team wants last quarter's orders in Excel; a migration from another platform arrives as one enormous product export.-### Import/Export System Diagram+Spree handles both directions as background work, so a hundred-thousand-row file doesn't tie up a browser tab or time out.```mermaid-erDiagram- Import {- string number- string type- string status- bigint owner_id- string owner_type- bigint user_id- }-- ImportMapping {- string schema_field- string file_column- }-- ImportRow {- integer row_number- text data- string status- text validation_errors- }-- ImportSchema {- array fields- }-- RowProcessor {- hash attributes- }-- Export {- string number- string type- integer format- jsonb search_params- }-- Store {- string name- }-- Import ||--|| Store : "belongs to (owner)"- Import ||--o{ ImportMapping : "has many"- Import ||--o{ ImportRow : "has many"- Import ||--|| ImportSchema : "uses"- ImportRow ||--|| RowProcessor : "processed by"- Export ||--|| Store : "belongs to"+flowchart LR+ File["CSV file"] --> Upload["Upload"]+ Upload --> Map["Match columns<br/>to fields"]+ Map --> Process["Process rows"]+ Process --> Good["Imported"]+ Process --> Bad["Failed rows<br/>with reasons"]+ Bad --> Retry["Fix and retry"]```-## Architecture+## What can be imported and exported-The import/export system uses several design patterns:+| Data | Import | Export |+|---|:---:|:---:|+| Products | Yes | Yes |+| Product translations | Yes | Yes |+| Customers | Yes | Yes |+| Orders | — | Yes |+| Gift cards | — | Yes |+| Coupon codes | — | Yes |+| Newsletter subscribers | — | Yes |-1. **Single Table Inheritance (STI)**: Import and Export types inherit from base classes-2. **State Machine**: Imports progress through states (pending → mapping → processing → completed)-3. **Schema Definition**: ImportSchema classes define expected fields and validation-4. **Row Processors**: Transform CSV rows into database records-5. **Event-Driven Processing**: Background jobs handle heavy lifting asynchronously-6. **Registry Pattern**: Types registered in `Spree.import_types` and `Spree.export_types`+Orders are export-only on purpose. An order is a financial record of something that happened; inventing them from a spreadsheet would let the books say something that never occurred.------## Exports--Exports generate CSV files from filtered database records.--### Built-in Export Types--| Type | Description | Multi-line |-|------|-------------|------------|-| `Spree::Exports::Products` | Products with all variants | Yes |-| `Spree::Exports::ProductTranslations` | Product translations for non-default store locales | Yes |-| `Spree::Exports::Orders` | Orders with line items | Yes |-| `Spree::Exports::Customers` | Customer accounts | No |-| `Spree::Exports::GiftCards` | Gift cards | No |-| `Spree::Exports::NewsletterSubscribers` | Newsletter subscribers | No |-| `Spree::Exports::CouponCodes` | Promotion coupon codes | No |--### Export Model--The base `Spree::Export` class provides:--```ruby-module Spree- class Export < Spree.base_class- # Associations- belongs_to :store- belongs_to :user # Admin who created export-- # Attachments- has_one_attached :attachment # Generated CSV file-- # Key methods- def csv_headers # Define column headers- def scope # Base query with store/vendor filtering- def scope_includes # Eager loading associations- def records_to_export # Apply ransack filters- def multi_line_csv? # True if records produce multiple rows- def generate # Create CSV and attach file- end-end-```--### Creating a Custom Exporter--**Step 1: Create the Export Class**--```ruby app/models/spree/exports/subscriptions.rb-module Spree- module Exports- class Subscriptions < Spree::Export- # Define CSV column headers- def csv_headers- %w[id email plan_name status created_at] + metafields_headers- end-- # Eager load associations to avoid N+1 queries- def scope_includes- [:user, :plan, { metafields: :metafield_definition }]- end-- # Override scope if needed (e.g., exclude cancelled)- def scope- super.where.not(status: 'cancelled')- end-- # Set to true if each record produces multiple CSV rows- def multi_line_csv?- false- end- end- end-end-```--**Step 2: Add `to_csv` Method to Your Model**--```ruby app/models/spree/subscription.rb-module Spree- class Subscription < Spree.base_class- def to_csv(store)- [- id,- user&.email,- plan&.name,- status,- created_at.iso8601- ] + metafields_csv_values(store)- end-- private-- def metafields_csv_values(store)- Spree::MetafieldDefinition.for_resource_type(self.class.name).order(:namespace, :key).map do |definition|- metafields.find { |m| m.metafield_definition_id == definition.id }&.value- end- end- end-end-```--**Step 3: Register the Export Type**--```ruby config/initializers/spree.rb-Rails.application.config.after_initialize do- Spree.export_types << Spree::Exports::Subscriptions-end-```--**Step 4: Add Translations**--```yaml config/locales/en.yml-en:- spree:- subscriptions: Subscriptions-```--### Multi-line Exports--For exports where each record produces multiple rows (like products with variants):--```ruby app/models/spree/exports/orders_with_items.rb-module Spree- module Exports- class OrdersWithItems < Spree::Export- def multi_line_csv?- true- end-- def csv_headers- %w[order_number line_item_sku quantity price]- end-- def scope_includes- [line_items: :variant]- end- end- end-end-```--```ruby app/models/spree/order.rb-# In the Order model-def to_csv(store)- line_items.map do |item|- [number, item.variant.sku, item.quantity, item.price]- end-end-```--### Export Filtering--Exports support [Ransack filtering via `search_params`](/api-reference/admin-api/querying):--```ruby-# In admin, users can filter before exporting-export = Spree::Exports::Products.new(- store: current_store,- user: current_user,- search_params: { name_cont: 'shirt', status_eq: 'active' }.to_json,- record_selection: 'filtered' # or 'all' to ignore filters-)-```-------## Imports--Imports process CSV files to create or update database records.--### Built-in Import Types--| Type | Description |-|------|-------------|-| `Spree::Imports::Products` | Products and variants |-| `Spree::Imports::ProductTranslations` | Product translations (matched by slug) |-| `Spree::Imports::Customers` | Customers |--### Import Workflow--```-1. Upload CSV → pending-2. Auto-map columns → mapping-3. User confirms mapping → completed_mapping-4. Parse rows (CreateRowsJob) → processing-5. Process rows (ProcessRowsJob) → completed/failed-```--### Import Components--#### Import Model--```ruby-module Spree- class Import < Spree.base_class- # Associations- belongs_to :owner, polymorphic: true # Store or Vendor- belongs_to :user- has_many :mappings # Field mappings- has_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-- # Key methods- def import_schema # Returns schema class instance- def row_processor_class # Returns processor class- def schema_fields # Fields from schema + metafields- def mapping_done? # All required fields mapped?- end-end-```--#### Import Schema--Defines expected CSV fields:--```ruby-module Spree- class ImportSchema- FIELDS = []+## Exporting- def fields- self.class::FIELDS- end+An export is created, runs in the background, and produces a file to download.- def required_fields- FIELDS.select { |f| f[:required] }.map { |f| f[:name] }- end+<CodeGroup>- def optional_fields- FIELDS.reject { |f| f[:required] }.map { |f| f[:name] }- end- end-end-```--#### Import Mapping--Maps CSV columns to schema fields:--```ruby-module Spree- class ImportMapping < Spree.base_class- belongs_to :import-- # Attributes- # schema_field - target field name from schema- # file_column - CSV column header-- def try_to_auto_assign_file_column(csv_headers)- # Matches by parameterized name comparison- self.file_column = csv_headers.find do |header|- header.parameterize.underscore == schema_field.parameterize.underscore- end- end- end-end-```--#### Import Row--Represents a single CSV row:--```ruby-module Spree- class ImportRow < Spree.base_class- belongs_to :import, counter_cache: :rows_count- belongs_to :item, polymorphic: true, optional: true # Created record-- # Attributes- # row_number - position in CSV- # data - JSON-serialized row data- # status - pending/processing/completed/failed- # validation_errors - error message if failed-- def process!- start_processing!- self.item = import.row_processor_class.new(self).process!- complete!- rescue StandardError => e- self.validation_errors = e.message- fail!- end-- def to_schema_hash- # Maps CSV data using import.mappings- end- end-end-```--#### Row Processor--Transforms row data into database records:--```ruby-module Spree- module Imports- module RowProcessors- class Base- def initialize(row)- @row = row- @import = row.import- @attributes = row.to_schema_hash- end-- attr_reader :row, :import, :attributes-- def process!- raise NotImplementedError- end- end- end- end-end-```--### Creating a Custom Importer--**Step 1: Create the Import Class**--```ruby app/models/spree/imports/subscriptions.rb-module Spree- module Imports- class Subscriptions < Spree::Import- def row_processor_class- Spree::Imports::RowProcessors::Subscription- end- end- end-end-```+```typescript Admin SDK+const exportJob = await adminClient.exports.create({+ type: 'Spree::Exports::Products',+})-**Step 2: Define the Schema**--```ruby app/models/spree/import_schemas/subscriptions.rb-module Spree- module ImportSchemas- class Subscriptions < Spree::ImportSchema- FIELDS = [- { name: 'email', label: 'Customer Email', required: true },- { name: 'plan_name', label: 'Plan Name', required: true },- { name: 'status', label: 'Status', required: true },- { name: 'start_date', label: 'Start Date' },- { name: 'billing_interval', label: 'Billing Interval' },- { name: 'amount', label: 'Amount' },- { name: 'currency', label: 'Currency' }- ].freeze- end- end-end+// Poll until it's done+const status = await adminClient.exports.get(exportJob.id)+status.status // "pending" → "processing" → "completed"+status.download_url // available once completed```-**Step 3: Create the Row Processor**--```ruby app/services/spree/imports/row_processors/subscription.rb-module Spree- module Imports- module RowProcessors- class Subscription < Base- def process!- user = find_or_create_user- plan = find_plan-- subscription = Spree::Subscription.find_or_initialize_by(- user: user,- plan: plan- )-- subscription.status = attributes['status'] if attributes['status'].present?- subscription.start_date = parse_date(attributes['start_date']) if attributes['start_date'].present?- subscription.billing_interval = attributes['billing_interval'] if attributes['billing_interval'].present?-- if attributes['amount'].present?- currency = attributes['currency'].presence || import.store.default_currency- subscription.set_price(currency, attributes['amount'])- end-- subscription.save!- subscription- end-- private-- def find_or_create_user- email = attributes['email'].strip.downcase- Spree.user_class.find_or_create_by!(email: email)- end-- def find_plan- Spree::Plan.find_by!(name: attributes['plan_name'].strip)- end-- def parse_date(date_string)- Date.parse(date_string)- rescue ArgumentError- nil- end- end- end- end-end+```bash CLI+spree api post /exports -d '{"type": "Spree::Exports::Products"}'+spree api get /exports```-**Step 4: Register the Import Type**+</CodeGroup>-```ruby config/initializers/spree.rb-Rails.application.config.after_initialize do- Spree.import_types << Spree::Imports::Subscriptions-end-```--**Step 5: Add Translations**+### Exporting a filtered set-```yaml config/locales/en.yml-en:- spree:- subscriptions: Subscriptions-```+An export can carry the same filters as the listing it came from, so "export what I'm looking at" does what a merchant expects — this quarter's orders, this brand's products, not the entire table.-### Products Import Schema--The built-in products import supports these fields:--**Required Fields:**-- `slug` - Product URL slug-- `sku` - Variant SKU-- `name` - Product name-- `price` - Variant price--**Optional Fields:**-- `status` - Product status (active/draft/archived)-- `description` - Product description-- `meta_title`, `meta_description`, `meta_keywords` - SEO metadata-- `tags` - Product tags-- `compare_at_price` - Original price for sale display-- `currency` - Price currency-- `width`, `height`, `depth`, `dimensions_unit` - Dimensions-- `weight`, `weight_unit` - Weight-- `available_on`, `discontinue_on` - Availability dates-- `track_inventory` - Enable inventory tracking-- `inventory_count`, `inventory_backorderable` - Stock settings-- `tax_category`, `shipping_category` - Category assignments-- `image1_src`, `image2_src`, `image3_src` - Image URLs-- `option1_name`, `option1_value` through `option3_name`, `option3_value` - Variant options-- `category1`, `category2`, `category3` - Taxon assignments (format: "Taxonomy -> Taxon -> Child Taxon")--### Handling Multi-Variant Products--The products import handles variants intelligently:--1. **Master variant rows** (no option values): Create/update the product and its master variant-2. **Non-master variant rows** (with option values): Create additional variants for an existing product--```csv-slug,sku,name,price,option1_name,option1_value,option2_name,option2_value-my-tshirt,TSHIRT-001,My T-Shirt,29.99,,,,-my-tshirt,TSHIRT-S-RED,My T-Shirt,29.99,Size,Small,Color,Red-my-tshirt,TSHIRT-M-RED,My T-Shirt,29.99,Size,Medium,Color,Red-my-tshirt,TSHIRT-L-RED,My T-Shirt,29.99,Size,Large,Color,Red+```typescript Admin SDK+await adminClient.exports.create({+ type: 'Spree::Exports::Orders',+ filters: { completed_at_gteq: '2026-01-01' },+})```-### Metafield Support--Both imports and exports support metafields dynamically:--**Export:** Metafield definitions are automatically added as CSV columns using the format `metafield.{namespace}.{key}`.+In the dashboard this is the Export button on any list — whatever filters are applied come along.-**Import:** Map CSV columns to metafield definitions. The system automatically detects columns matching the metafield pattern and updates the corresponding metafield values.+## Importing----+Importing has an extra step, because a file from somewhere else won't have Spree's column names. You upload it, say which of your columns means what, and then it runs.-## Background Jobs+<Steps>+ <Step title="Upload the file">+ ```typescript Admin SDK+ const importJob = await adminClient.imports.create({+ type: 'Spree::Imports::Products',+ file: uploadedFileId,+ })+ ```-### CreateRowsJob+ Spree reads the header row and tells you which columns it found.+ </Step>+ <Step title="Match columns to fields">+ ```typescript Admin SDK+ await adminClient.imports.completeMapping(importJob.id, {+ mappings: [+ { schema_field: 'name', file_column: 'Product Title' },+ { schema_field: 'sku', file_column: 'Item Code' },+ { schema_field: 'price', file_column: 'RRP' },+ ],+ })+ ```-Parses CSV and creates ImportRow records:+ Obvious matches are suggested for you; you only correct the ones that differ.+ </Step>+ <Step title="Watch it run">+ ```typescript Admin SDK+ const status = await adminClient.imports.get(importJob.id)-All import jobs inherit from `Spree::Imports::BaseJob`, which sets `queue_as Spree.queues.imports` once and is shared across the pipeline.+ status.status // "processing" → "completed"+ status.rows_count // total+ status.processed_count+ status.failed_count+ ```+ </Step>+</Steps>-```ruby-module Spree- module Imports- class CreateRowsJob < Spree::Imports::BaseJob- def perform(import_id)- import = Spree::Import.find(import_id)- # Stream CSV, batch insert rows- # Then enqueue ProcessRowsJob via import.process_rows_async- end- end- end-end-```+<Info>+Download a template for any import type to see the expected columns — the quickest way to prepare a file that maps cleanly.+</Info>-### ProcessRowsJob--Fans the pending rows out into groups, each processed by a separate `ProcessGroupJob`:--```ruby-module Spree- module Imports- class ProcessRowsJob < Spree::Imports::BaseJob- BATCH_SIZE = 100-- def perform(import_id)- import = Spree::Import.find(import_id)- dispatch_groups(import)- end-- private-- def dispatch_groups(import)- # When the import defines a group_column (e.g. ProductTranslations groups- # by slug) and that field is mapped, group rows by the column value.- # Otherwise, fall back to slicing pending_and_failed rows into batches of- # BATCH_SIZE. Either way: pluck the row IDs, set processing_groups_count /- # completed_groups_count up front so workers can't complete prematurely,- # then enqueue one ProcessGroupJob per group.- import.rows.pending_and_failed.in_batches(of: BATCH_SIZE) do |batch|- ProcessGroupJob.perform_later(import.id, batch.ids)- end- end- end- end-end-```+## When rows fail-### ProcessGroupJob--Processes one group of rows and reports completion:--```ruby-module Spree- module Imports- class ProcessGroupJob < Spree::Imports::BaseJob- def perform(import_id, row_ids)- import = Spree::Import.find(import_id)- rows = import.rows.where(id: row_ids).pending_and_failed-- # Large imports process with events disabled and use bulk_process!;- # otherwise each row is processed individually via row.process!.- rows.each { |row| row.process! }-- check_import_completion(import)- end-- private-- # Increments completed_groups_count, then completes the import only once the- # last group has finished and no rows are still in flight.- def check_import_completion(import)- # completed_groups_count += 1- import.complete! if import.completed_groups_count >= import.processing_groups_count &&- import.rows.in_flight.none?- end- end- end-end-```+Some rows will fail. A price with a currency symbol in it, a required field left blank, a duplicate SKU.-### GenerateJob (Exports)+**A failed row doesn't stop the import.** The good rows are imported; the bad ones are set aside with the reason.-Generates CSV files for exports:+```typescript Admin SDK+const { data: failures } = await adminClient.imports.rows.list(importJob.id, {+ filter: { status_eq: 'failed' },+})-```ruby-module Spree- module Exports- class GenerateJob < Spree::BaseJob- queue_as Spree.queues.exports+failures.forEach((row) => {+ row.row_number // 47+ row.validation_errors // "Price is not a number"+})- def perform(export_id)- export = Spree::Export.find_by_prefix_id!(export_id)- export.generate- end- end- end-end+// After fixing the source data+await adminClient.imports.retryFailedRows(importJob.id)```------## Events--Import and export lifecycle events such as [`import.completed` and `export.created`](/api-reference/webhooks-events) can be delivered as webhooks to react when an asynchronous import or export finishes.--### Import Events--| Event | Trigger |-|-------|---------|-| `import.created` | Import record created |-| `import.completed` | All rows processed |--### Export Events+Retrying re-runs only the failures, so a file where three rows out of ten thousand were wrong doesn't need re-importing whole.-| Event | Trigger |-|-------|---------|-| `export.created` | Export record created (triggers generation) |+<Warning>+A value that isn't a number is rejected, never guessed at. A price written as `"12,50"` fails rather than being read as `1250` — which would be a hundredfold overcharge. Fix the file rather than hoping the import is lenient.+</Warning>-### Import Row Events+## Interrupted work resumes-| Event | Trigger |-|-------|---------|-| `import_row.completed` | Row processed successfully |-| `import_row.failed` | Row processing failed |+Imports remember which row they reached. If the server restarts halfway through a large file, processing picks up where it stopped rather than starting again or skipping the remainder.------## Configuration--### Queue Configuration--```ruby config/initializers/spree.rb-# Configure job queues-Spree.queues.imports = :imports-Spree.queues.exports = :exports-```+## Products with several variants-### Preferences+A product with variants spans several rows — one per variant, repeating the product columns. Rows are grouped by the product identifier, so a t-shirt in three sizes is three rows and becomes one product.-Imports support configurable delimiter:+Custom fields can be imported too: a column matching a [custom field](/developer/core-concepts/metafields) you've defined maps to it like any built-in field.-```ruby-import.preferred_delimiter = ';' # Default: ','-```+## Knowing when it's finished----+Imports and exports emit [events](/developer/core-concepts/events) as they progress, which also reach [webhooks](/developer/core-concepts/webhooks). That's how you trigger the next step of a pipeline — notify a channel, kick off a reindex — without polling.-## Key Files Reference--| File | Purpose |-|------|---------|-| `core/app/models/spree/import.rb` | Base import model |-| `core/app/models/spree/export.rb` | Base export model |-| `core/app/models/spree/import_schema.rb` | Base schema class |-| `core/app/models/spree/import_mapping.rb` | Field mapping model |-| `core/app/models/spree/import_row.rb` | Row model with processing |-| `core/app/models/spree/imports/products.rb` | Products import type |-| `core/app/models/spree/import_schemas/products.rb` | Products schema |-| `core/app/services/spree/imports/row_processors/base.rb` | Base processor |-| `core/app/services/spree/imports/row_processors/product_variant.rb` | Products processor |-| `core/app/models/spree/exports/products.rb` | Products export |-| `core/app/models/spree/exports/orders.rb` | Orders export |-| `core/app/models/spree/exports/customers.rb` | Customers export |-| `core/app/jobs/spree/imports/create_rows_job.rb` | Row creation job |-| `core/app/jobs/spree/imports/process_rows_job.rb` | Row processing job |-| `core/app/jobs/spree/exports/generate_job.rb` | Export generation job |-| `admin/app/controllers/spree/admin/imports_controller.rb` | Admin imports controller |-| `admin/app/controllers/spree/admin/exports_controller.rb` | Admin exports controller |+| Event | When |+|---|---|+| `import.completed` | Every row has been attempted |+| `import.failed` | The import could not run |+| `export.completed` | The file is ready to download |## Permissions-Access is controlled via CanCanCan:--```ruby-# Allow admin to manage imports/exports-can :manage, Spree::Import-can :manage, Spree::Export-```--Records are filtered by `current_ability` ensuring users only export data they have access to.+Import and export are gated by the same [permissions](/developer/core-concepts/staff-roles) as the data they touch. Someone who can't see customers can't export them — otherwise export would be a way around the whole permission system.-## Related Documentation+## Related-- [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.+- [Products](/developer/core-concepts/products) — the most-imported data+- [Custom Fields](/developer/core-concepts/metafields) — importing your own fields+- [Events](/developer/core-concepts/events) — reacting to completion+- [Staff & Roles](/developer/core-concepts/staff-roles) — who may import and exportdiff --git a/docs/developer/core-concepts/inventory.mdx b/docs/developer/core-concepts/inventory.mdxindex 729f319e0c..9310ae07de 100644--- a/docs/developer/core-concepts/inventory.mdx+++ b/docs/developer/core-concepts/inventory.mdx@@ -1,335 +1,199 @@---title: Inventory-description: Stock locations, stock items, stock movements, and inventory tracking+description: How Spree tracks stock across locations — what's on hand, what's spoken for, and what a shopper is allowed to buy.----import { Since } from '/snippets/since.mdx';-## Overview-Each [Variant](/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.+Inventory answers one question a shopper cares about — *can I buy this?* — and several a merchant cares about: where is it, how much is left, and what happened to the rest.-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+Spree tracks stock **per location**. A variant doesn't have "a stock count"; it has a count at each warehouse or shop that carries it. That's what makes it possible to ship from the nearest location, or to let a customer collect in store.```mermaiderDiagram- StockLocation {- string name- string admin_name- boolean active- boolean default- boolean backorderable_default- boolean propagate_all_variants- }-- StockItem {+ Variant ||--o{ StockLevel : "stocked at each location"+ StockLocation ||--o{ StockLevel : "holds"+ StockLevel ||--o{ StockMovement : "changed by"+ StockLevel ||--o{ StockReservation : "held by checkouts"+ Order ||--o{ Fulfillment : "ships as"+ Fulfillment ||--o{ FulfillmentItem : "contains"++ StockLevel {integer count_on_hand+ integer allocated_countboolean 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 {+ string name+ boolean active+ string country_code}-- 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](/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--### Stock Locations+## The three numbers-Stock Locations are the physical locations where your inventory is stored and shipped from.+A stock level carries two counts, and a third is derived from them. Keeping them apart is what stops a warehouse from disagreeing with a website.-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:+| | What it means |+|---|---|+| `count_on_hand` | What is physically on the shelf, right now |+| `allocated_count` | How much of that is already spoken for by orders not yet shipped |+| **`available_count`** | `count_on_hand − allocated_count` — what's actually sellable |-| 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` |+<Note>+**Selling an item does not reduce `count_on_hand`.** Placing an order raises `allocated_count`; the physical count only drops when the parcel actually ships.-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.+This is deliberate. Until it leaves the building, the stock *is* still on the shelf — and a warehouse worker counting boxes should find the number Spree reports. Overselling shows up honestly as `allocated_count` exceeding what's on hand, rather than as an impossible negative count.+</Note>-You can easily use them with your Point of Sale (POS) system to track inventory at different locations.+## Stock locations-Create and manage stock locations via the [Admin API](/api-reference/admin-api/introduction):+A stock location is somewhere stock physically sits: a warehouse, a shop, a third-party fulfillment centre.-<CodeGroup>+| Attribute | Description |+|---|---|+| `name` | What staff call it |+| `active` | Whether it can be used for new orders |+| `default` | Used first when nothing else decides |+| `country_code`, `state_code`, `city`, `postal_code` | Where it is — used for shipping rates and for finding the nearest one |+| `backorderable_default` | Whether new stock levels here allow backorders |+| `fulfillable` | Whether orders can ship from here, or it's display-only stock |+| `pickup` | Whether customers can collect here |```typescript Admin SDK-import { createAdminClient } from '@spree/admin-sdk'+const { data: locations } = await adminClient.stockLocations.list()-const client = createAdminClient({- baseUrl: 'https://store.example.com',- secretKey: 'sk_xxx',+await adminClient.stockLocations.create({+ name: 'Berlin Warehouse',+ country_code: 'DE',+ city: 'Berlin',+ active: true,})--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.+## Reading and adjusting stock-| 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:+A stock level is the intersection of a variant and a location. They're created for you — for every variant when a location propagates all variants, or as variants are added.<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' })+// Stock for one location+const { data: levels } = await adminClient.stockLevels.list({+ filter: { stock_location_id_eq: 'sl_xxx' },+})-await client.stockItems.update('si_xxx', {+// Correct a single count+await adminClient.stockLevels.update('slv_xxx', {count_on_hand: 150,backorderable: true,})++// Set many at once — the right call for a nightly sync+await adminClient.stockLevels.bulkUpsert({+ stock_levels: [+ { variant_id: 'var_xxx', stock_location_id: 'sl_xxx', count_on_hand: 40 },+ { variant_id: 'var_yyy', stock_location_id: 'sl_xxx', count_on_hand: 12 },+ ],+})``````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}'+spree api get '/stock_levels?q[stock_location_id_eq]=sl_xxx'+spree api patch /stock_levels/slv_xxx -d '{"count_on_hand": 150}'```</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:+<Warning>+Use `bulkUpsert` for feeds from a warehouse or ERP rather than a loop of single updates. It's one request instead of thousands, and it won't half-apply if the connection drops.+</Warning>-| 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` |+## Stock movements-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:+Every change to stock is recorded as a movement, so "why is this number what it is" always has an answer.-<CodeGroup>+| Kind | When it happens |+|---|---|+| `received` | New stock arrives |+| `allocated` | An order claims stock — `allocated_count` goes up |+| `shipped` | A parcel leaves — `count_on_hand` goes down, the allocation is retired |+| `released` | An allocation is given back, because an order was cancelled |+| `adjusted` | A manual correction, such as after a stock count |```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 },- ],+const { data: movements } = await adminClient.stockMovements.list({+ filter: { variant_id_eq: 'var_xxx' },})```-```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.+Each movement points at what caused it — the order, the fulfillment, the transfer — so an audit trail reads as a sequence of business events rather than a list of numbers that changed.-### Stock Movements+## What a shopper sees-Stock Movements track the movement of the inventory:+For a storefront, all of the above collapses into one question, and the answer is already computed:-* 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+```typescript Store SDK+const product = await client.products.get('spree-tote')-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" />+product.variants.forEach((variant) => {+ variant.in_stock // can it be bought right now+ variant.purchasable // in stock, or backorderable+})+```-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.+`in_stock` already accounts for what's allocated and what other shoppers are holding in checkout. There is nothing to compute client-side, and no separate inventory request to make.-### What changes for the storefront+## Reservations during checkout-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.+Without reservations, two customers can both see the last unit, both start checkout, and one discovers at the payment step that it's gone. That's a bad moment to find out.-### Lifecycle+A reservation is a short, time-limited hold placed when a customer enters checkout. Availability drops for everyone else immediately.-| Trigger | Action |+| Moment | What happens ||---|---|-| 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.+| Customer enters checkout | Their items are held, with an expiry |+| They keep editing the cart | The expiry is pushed forward |+| They complete the order | The hold becomes a real allocation |+| They abandon it | The hold expires and stock returns |-### Insufficient stock during checkout+Reservations never touch `count_on_hand` — they're a separate layer consulted when availability is read. A backorderable item is skipped entirely, since unlimited supply needs no holding.-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.+How long the hold lasts is a **store setting**, because it's a decision about the checkout experience rather than a property of a warehouse. Reservations can also be switched off entirely.-### 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.+<Info>+Expired reservations are cleaned up by a background job. Spree ships the job but does not schedule it — your app's job runner should run it every minute or so.+</Info>-## Inventory Units+## Backorders-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.+A stock level marked `backorderable` can be sold past zero. Orders are accepted, allocated, and wait for stock.-We create `InventoryUnit` objects when:+When new stock arrives, backorders are filled first, and only the remainder becomes available to new customers — so the people who waited longest aren't overtaken by whoever happens to visit the site next.-* a product is sold (they are added to the Shipment)-* a product is returned+## Moving stock between locations-Here's a list of attributes for the Inventory Unit model:+A stock transfer moves inventory from one location to another, and reflects that this takes time: stock is booked out of the source, is in transit, and is received at the destination — where a partial receipt is a normal outcome, because sometimes not everything arrives.-| 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` |+```typescript Admin SDK+const { data: transfers } = await adminClient.stockTransfers.list()+```-Inventory Units states are:+## Turning tracking off-* `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+Some things don't need counting — a service, a made-to-order item, a digital download. Tracking can be switched off, and those variants are always purchasable.-<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>+This is a store-level setting, so a store that sells only digital goods needn't manage stock at all.-## Disabling Inventory Tracking+## Syncing from an external system-If you don't need to track inventory, you can disable it:+If your inventory truth lives in an ERP or a warehouse system, Spree can defer to it. The rule that matters: **the read path stays local.** Whether a variant is in stock is answered from Spree's own data, not by calling out to another system while a shopper waits for a product page.-- **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+Feeds come in through the bulk update above; live checks happen only at decision moments, like completing an order. See [Providers](/developer/providers/overview).-## Related Documentation+## Related-- [Products](/developer/core-concepts/products) - Product and variant management-- [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 calls+- [Products](/developer/core-concepts/products) — variants, the things stock is counted for+- [Fulfillments](/developer/core-concepts/fulfillments) — how stock leaves the building+- [Orders](/developer/core-concepts/orders) — where allocation happens+- [Carts](/developer/core-concepts/carts) — checkout and reservationsdiff --git a/docs/developer/core-concepts/markets.mdx b/docs/developer/core-concepts/markets.mdxindex a08e65cfc9..171e65c257 100644--- a/docs/developer/core-concepts/markets.mdx+++ b/docs/developer/core-concepts/markets.mdx@@ -3,10 +3,6 @@ title: Marketsdescription: Configure Spree Markets to bundle geography, currency, and locale into distinct selling regions and run multi-region commerce from a single store.----import { Since } from '/snippets/since.mdx';--<Since version="5.4" />-## OverviewMarkets let you segment a single [Store](/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:@@ -51,14 +47,14 @@ erDiagram| `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" }]` |+| `country_codes` | Countries in this market, as ISO codes | `["US", "CA"]` |## How Markets WorkWhen 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+Customer's Country → Market → Currency + Locale + Tax treatment```The resolution chain:@@ -66,7 +62,7 @@ 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 country3. 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+4. The market's tax setting determines whether prices are shown with or without taxIf no market matches the customer's country, the store's **default market** is used.@@ -226,9 +222,9 @@ The `tax_inclusive` flag on a market controls how prices are displayed and calcu- **`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.+This matters because prices are shown long before anyone knows where the shopper lives. The market's own country supplies the assumed rate for browsing; once a shipping address is entered at checkout, that address takes over and the real rate applies.-See [Taxes](/developer/core-concepts/taxes) for details on tax zones and rates.+A market also chooses **which tax provider works out its numbers** — Spree's own rate tables in a simple market, an external tax service in a complicated one. See [Taxes](/developer/core-concepts/taxes).## Pricing Integration@@ -259,7 +255,7 @@ const northAmerica = await client.markets.create({name: 'North America',currency: 'USD',default_locale: 'en',- country_isos: ['US', 'CA'],+ country_codes: ['US', 'CA'],default: true,})@@ -270,7 +266,7 @@ const europe = await client.markets.create({default_locale: 'de',supported_locales: ['de', 'en', 'fr'],tax_inclusive: true,- country_isos: ['DE', 'FR', 'AT', 'NL'],+ country_codes: ['DE', 'FR', 'AT', 'NL'],})```@@ -279,7 +275,7 @@ spree api post /markets -d '{"name": "North America","currency": "USD","default_locale": "en",- "country_isos": ["US", "CA"],+ "country_codes": ["US", "CA"],"default": true}'```@@ -306,6 +302,6 @@ spree api delete /markets/market_xxx- [Markets (Store SDK)](/developer/sdk/store/markets) — Listing, resolving, and reading markets from the Store SDK- [Pricing](/developer/core-concepts/pricing) — Price Lists, Price Rules, and the Pricing Context-- [Addresses](/developer/core-concepts/addresses) — Countries, States, and Zones+- [Addresses](/developer/core-concepts/addresses) — Countries, states, and address forms- [Localization](/api-reference/store-api/localization) — Locale, currency, and country headers in API requests- [Translations](/developer/core-concepts/translations) — Resource and UI translationsdiff --git a/docs/developer/core-concepts/media.mdx b/docs/developer/core-concepts/media.mdxindex f8b8044d63..315d1b1ab5 100644--- a/docs/developer/core-concepts/media.mdx+++ b/docs/developer/core-concepts/media.mdx@@ -4,8 +4,6 @@ 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.----import { Since } from '/snippets/since.mdx';-## OverviewSpree handles uploads, processing, and delivery for product media. Images are automatically converted to WebP format and preprocessed into multiple sizes for optimal performance.@@ -21,7 +19,7 @@ A media record carries:- **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" />+### Product-level GalleryIn 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.@@ -114,7 +112,7 @@ The Store API's `media` field on a product returns its gallery — product-levelThis 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" />+### VideoA product gallery can hold video as well as images. Spree supports both ways merchants usually have it:@@ -198,7 +196,7 @@ Where the poster comes from, in order: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`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.@@ -211,7 +209,7 @@ await client.products.media.update('prod_86Rf07xd4z', 'media_k5nR8xLq', {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" />+### Named Variant SizesWhen an image is uploaded, Spree automatically generates optimized versions in the background:@@ -337,13 +335,13 @@ curl 'https://api.mystore.com/api/v3/store/products/spree-tote?expand=media,vari| `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" /> |+| `video_provider` | string \| null | `youtube` or `vimeo`, derived from the link |+| `video_embed_url` | string \| null | Embeddable player URL, derived from the link |+| `video_url` | string \| null | Uploaded video file URL |+| `poster_url` | string \| null | Still frame for a video || `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" /> |+| `download_url` | string \| null | Same blob as `original_url` but with `Content-Disposition: attachment`. Admin API only. |## Image Processingdiff --git a/docs/developer/core-concepts/metafields.mdx b/docs/developer/core-concepts/metafields.mdxindex cdc54d7f2b..86cf52f329 100644--- a/docs/developer/core-concepts/metafields.mdx+++ b/docs/developer/core-concepts/metafields.mdx@@ -1,155 +1,133 @@----title: Metafields-description: Add custom structured data to products, orders, and other resources with type-safe metafields+title: Custom Fields+description: Add your own structured, typed data to products, orders and other records — searchable, filterable, and editable in the dashboard.----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](/developer/customization/metadata) which is simple JSON storage, metafields are schema-defined with strong typing, validation, and visibility controls.+Sooner or later you need to store something Spree doesn't have a field for. A fabric composition. A care instruction. A gift message. An ID from the system you sync with.-Use metafields for:+Custom fields are how you do that without changing the database. You declare a field once — its name, its type, who can see it — and from then on it can be set on any record of that kind, edited in the dashboard, returned by the API, and searched or filtered like any built-in field.-- Product specifications (manufacturer, material, dimensions)-- Custom business logic fields-- Integration data from external systems-- Order-specific custom attributes+<Note>+Custom fields were called **metafields** before Spree 6.0. The API and SDK have always called them custom fields; now the rest of Spree does too.+</Note>-## Architecture+## Definitions and values++There are two halves, and it helps to keep them straight:```mermaiderDiagram- MetafieldDefinition ||--o{ Metafield : "defines schema for"- Product ||--o{ Metafield : "has many"- Variant ||--o{ Metafield : "has many"- Order ||--o{ Metafield : "has many"+ CustomFieldDefinition ||--o{ CustomField : "gives shape to"+ Product ||--o{ CustomField : "has values"+ Order ||--o{ CustomField : "has values"+ Customer ||--o{ CustomField : "has values"- MetafieldDefinition {+ CustomFieldDefinition {string namespacestring key- string name- string metafield_type+ string label+ string field_typestring resource_type- string display_on+ boolean storefront_visibleboolean searchableboolean sortable}- Metafield {- string type- text value- string resource_type+ CustomField {+ string key+ string label+ string field_type+ any value}```-```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+- A **definition** is the declaration: "products have a Material, it is short text, shoppers may see it." You create it once.+- A **custom field** is one record's answer: this product's material is `100% Cotton`.-| 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 |+Because the definition carries the type and the label, the dashboard can build an editing form for it automatically, and your storefront gets a value it can trust the shape of.-## Visibility Control+## Field types-Metafields support two visibility levels via the `display_on` attribute:+| Type | For | Example |+|---|---|---|+| `short_text` | A word or a line | `Wilson`, `100% Cotton` |+| `long_text` | A paragraph | Care instructions |+| `rich_text` | Formatted HTML | A spec sheet with lists and bold |+| `number` | A quantity or measure | `3.5`, `120` |+| `boolean` | A yes or no | Requires a signature |+| `json` | Structured data | A sizing chart |-| Visibility | Store API | Admin API | Use Case |-|------------|:---------:|:---------:|----------|-| `both` | Yes | Yes | Public product specifications |-| `back_end` | No | Yes | Internal notes, integration IDs |+## Who can see it-## Search, sort & filter+`storefront_visible` decides whether a field ever leaves the back office:-Product metafield definitions can opt into SearchProvider participation:+| `storefront_visible` | Store API | Admin API | Use it for |+|---|:---:|:---:|---|+| `true` | Yes | Yes | Anything a shopper should see — materials, specs |+| `false` | No | Yes | Internal notes, supplier codes, sync IDs |-| 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.+<Warning>+`storefront_visible: false` genuinely withholds the field from the Store API — it is not hidden in the response, it is absent. Treat it as the boundary between what a customer may read and what only staff may.+</Warning>-### Filtering+## Declaring a field-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:+<CodeGroup>+```typescript Admin SDK+const definition = await adminClient.customFieldDefinitions.create({+ resource_type: 'Spree::Product',+ namespace: 'properties',+ key: 'material',+ label: 'Material',+ field_type: 'short_text',+ storefront_visible: true,+ searchable: true,+})```-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+```bash CLI+spree api post /custom_field_definitions -d '{+ "resource_type": "Spree::Product",+ "namespace": "properties",+ "key": "material",+ "label": "Material",+ "field_type": "short_text",+ "storefront_visible": true,+ "searchable": true+}'+```-Metafields can be attached to most Spree resources including Products, Variants, Orders, Line Items, Taxons, Payments, Shipments, Gift Cards, Store Credits, and more.+</CodeGroup>-<Info>-Custom resources can also support metafields. See the [Customization Quickstart](/developer/customization/quickstart) for details.-</Info>+`namespace` keeps groups of fields apart, so an integration's `product_id` never collides with yours. Together they form the key you'll see in responses: `properties.material`. Both are normalized to snake_case.-## Namespaces+Definitions can also be managed in the dashboard under **Settings → Custom Fields**, which is where merchants usually add them.-Namespaces organize metafields into logical groups and prevent key conflicts:+## Setting and reading values-| 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 |+<CodeGroup>-<Info>-Namespace and key are automatically normalized to snake_case.-</Info>+```typescript Admin SDK+// Set a value on a product+await adminClient.products.customFields.create('prod_xxx', {+ custom_field_definition_id: definition.id,+ value: '100% Cotton',+})+```-## Store API+```bash CLI+spree api post /products/prod_xxx/custom_fields -d '{+ "custom_field_definition_id": "cfdef_xxx",+ "value": "100% Cotton"+}'+```-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):+</CodeGroup>-<Info>- Metafields in API are called Custom Fields as we plan to rename Metafields to Custom Fields completely in Spree 6.0.-</Info>+Reading them from a storefront is an expand on whatever you already fetch:<CodeGroup>@@ -158,45 +136,30 @@ 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'],+product.custom_fields?.forEach((field) => {+ field.key // "properties.material"+ field.label // "Material"+ field.value // "100% Cotton"+ field.field_type // "short_text"})``````bash cURLcurl 'https://api.mystore.com/api/v3/store/products/spree-tote?expand=custom_fields' \- -H 'X-Spree-Api-Key: pk_xxx'+ -H 'X-Spree-API-Key: pk_xxx'```</CodeGroup>-**Response:**--```json+```json Response{"id": "prod_86Rf07xd4z",- "name": "Spree T-Shirt",+ "name": "Spree Tote","custom_fields": [{"id": "cf_k5nR8xLq",- "label": "Manufacturer",- "key": "properties.manufacturer",- "field_type": "short_text",- "value": "Wilson"- },- {- "id": "cf_m3Rp9wXz",- "label": "Material","key": "properties.material",+ "label": "Material","field_type": "short_text","value": "100% Cotton"}@@ -204,104 +167,59 @@ curl 'https://api.mystore.com/api/v3/store/products/spree-tote?expand=custom_fie}```-<Note>-The `display_on` attribute is intentionally excluded from Store API responses for security.-</Note>--## Admin Management+Each value arrives with its own label and type, so you can render a spec table straight from the array without hardcoding which fields exist.-### Managing Definitions+## Searching, sorting and filtering-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.+A custom field can take part in product listings — but only if you ask, because indexing everything by default would be wasteful.-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:+| Flag | What it enables | Works with |+|---|---|---|+| `searchable` | The value is matched by product text search | `short_text`, `long_text`, `number` |+| `sortable` | Listings can be ordered by it | `short_text`, `number` |-<CodeGroup>--```typescript Admin SDK-import { createAdminClient } from '@spree/admin-sdk'+Setting either flag also makes the field **filterable**. Filter and sort with the field's `cf_` key, on both APIs:-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-}'+GET /api/v3/store/products?q[cf_properties_material_i_cont]=wool+GET /api/v3/store/products?sort=-cf_properties_weight+GET /api/v3/admin/products?q[cf_properties_weight_gteq]=3.5```-</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>+| Field type | Comparisons available |+|---|---|+| `short_text`, `long_text` | `i_cont`, `cont`, `eq`, `not_eq`, `start`, `end`, `present`, `blank` |+| `number` | `eq`, `gt`, `gteq`, `lt`, `lteq`, `present`, `blank` |-```typescript Admin SDK-await client.products.customFields.create('prod_xxx', {- custom_field_definition_id: 'cfdef_xxx',- value: 'Wilson',-})-```+Use `i_cont` for case-insensitive matching. A comparison that doesn't suit the field's type is ignored rather than rejected, so a stale filter in a saved view can't break a page.-```bash CLI-spree api post /products/prod_xxx/custom_fields -d '{- "custom_field_definition_id": "cfdef_xxx",- "value": "Wilson"-}'-```+<Info>+If you use Meilisearch, re-index after changing these flags so the new fields are picked up. Substring matching (`i_cont`, `cont`, `start`, `end`) is a database-provider feature; Meilisearch handles equality, ranges and presence. See [Search & Filtering](/developer/core-concepts/search-filtering).+</Info>-</CodeGroup>+In the dashboard, fields with these flags become available in the product table's column picker, sort menu and filter panel — off by default, so merchants opt in per column.-## Metafields vs Metadata+## What can carry custom fields-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.+Most things you'd want to annotate: products, variants, orders, line items, customers, categories, payments, fulfillments, gift cards and store credits, among others.-| Feature | Metafields | [Metadata](/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) |+## Custom fields or metadata?-**Use Metafields** when you need type validation, visibility control, admin UI forms, or organized namespacing.+Spree has two ways to store your own data, and they are not competing — they solve different problems.-**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.+| | Custom fields | [Metadata](/developer/customization/metadata) |+|---|---|---|+| **For** | Data a merchant curates | Data your code keeps |+| **Shape** | Declared and typed | Any JSON, no declaration |+| **Dashboard** | Proper edit forms | Raw JSON |+| **Visibility** | Configurable per field | Never read by the Store API |+| **Searchable** | Yes, opt in | Not through the product search |-<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>+Put it simply: **custom fields are for people, metadata is for machines.** If a merchant should type it, define a custom field. If it is a sync token or an external ID that only your integration reads, use metadata.-## Related Documentation+## Related-- [Metadata](/developer/customization/metadata) — Simple key-value metadata-- [Products](/developer/core-concepts/products) — Product catalog-- [Events](/developer/core-concepts/events) — Subscribe to metafield events-- [Admin SDK](/developer/sdk/admin/resources) — Manage definitions and values from TypeScript+- [Metadata](/developer/customization/metadata) — the machine-readable alternative+- [Products](/developer/core-concepts/products) — the most common place for custom fields+- [Search & Filtering](/developer/core-concepts/search-filtering) — how filters and search work+- [Admin SDK](/developer/sdk/admin/resources) — managing definitions and values in TypeScriptdiff --git a/docs/developer/core-concepts/order-totals.mdx b/docs/developer/core-concepts/order-totals.mdxnew file mode 100644index 0000000000..3bf8421853--- /dev/null+++ b/docs/developer/core-concepts/order-totals.mdx@@ -0,0 +1,114 @@+---+title: Order Totals+description: How an order total is built up from items, tax, discounts, delivery and fees — and how to render a summary that adds up.+---++## Overview++An order total is rarely just the sum of the item prices. Tax is added or already inside them, a promo code takes something off, delivery costs something, gift wrapping costs a bit more.++Spree records each of those as its own kind of row, and keeps a running total for each kind on the order itself. That means the summary block in your checkout is a handful of fields — you don't add anything up yourself.++```mermaid+flowchart TB+ Items["Item total"] --> Total["Order total"]+ Discounts["Discounts"] --> Total+ Delivery["Delivery"] --> Total+ Fees["Fees"] --> Total+ Tax["Tax"] --> Total++ style Total fill:#e8f5e9,stroke:#2e7d32+```++## The totals++```typescript Store SDK+const order = await client.orders.get('or_xxx')++order.display_item_total // "$120.00" items, before tax and discounts+order.display_discount_total // "-$12.00" everything taken off+order.display_delivery_total // "$5.00" delivery+order.display_fee_total // "$2.50" surcharges+order.display_tax_total // "$22.60" all tax+order.display_total // "$138.10" what the customer pays+```++| Attribute | What it sums |+|---|---|+| `item_total` | Line item prices, before tax and discounts |+| `discount_total` | Every [discount](/developer/core-concepts/discounts) |+| `delivery_total` | Delivery charges |+| `fee_total` | Every [fee](/developer/core-concepts/fees) |+| `tax_total` | All [tax](/developer/core-concepts/taxes) |+| `included_tax_total` | Tax already inside the displayed prices |+| `additional_tax_total` | Tax added on top |+| `total` | What the customer pays |+| `amount_due` | Still to pay, after gift cards and store credit |++## Two forms of every amount++Every total comes twice: `total` is the raw value, `display_total` is formatted for the order's currency.++```json+{+ "total": "138.10",+ "display_total": "$138.10"+}+```++**Render the `display_` one.** It knows the currency symbol, which side it goes on, and which separator that locale uses — `$138.10`, `138,10 €`, `¥138`. Formatting it yourself means reimplementing that, and getting it wrong for somebody.++<Note>+Money is a **string**, never a number. JavaScript can't represent every decimal exactly: `0.1 + 0.2` gives `0.30000000000000004`, which is not something you want inside a price.++If you must do arithmetic, use a decimal library or work in whole cents. Most of the time you don't need to — Spree already did it.+</Note>++## The double-counting trap++<Warning>+If you build a subtotal yourself, include `additional_tax_total` only — never `included_tax_total`.++Included tax is **already inside** the item prices. Adding it again charges the customer's eyes twice, and produces a summary that doesn't match the amount taken from their card. This is the single most common bug in a European storefront.+</Warning>++The two exist because the same order can carry both: VAT already inside the goods, and a separately-added tax on something else. `tax_total` covers both, which is why it's the safe field to display on its own line.++## Totals update themselves++Every change to a cart returns the whole cart, totals included:++```typescript Store SDK+const cart = await client.carts.items.create(cartId, {+ variant_id: 'var_xxx',+ quantity: 2,+})++cart.display_total // already correct+```++There is never a second "recalculate" request to make, and never a moment where the summary on screen disagrees with what the server thinks. Adding an item, entering an address, applying a code — each response carries the new numbers.++The totals are worked out again at the moment the cart is completed, so a price that changed while the customer sat on the review page can't lead to the wrong charge.++## Once an order is placed++The rows stop being regenerated. Editing a placed order re-adds the rows it already has rather than starting over, so today's promotions and rates can't rewrite what a customer agreed to last week.++## Where each row attaches++The individual rows are there if you need them — an itemised invoice, a tax report:++- **[Tax lines](/developer/core-concepts/taxes)** → a line item, a fulfillment, or a fee+- **[Discounts](/developer/core-concepts/discounts)** → a line item or a fulfillment+- **[Fees](/developer/core-concepts/fees)** → a line item, a fulfillment, or the order itself++Each row also keeps a copy of where it came from — the rate and label on a tax line, the code and promotion on a discount. If someone deletes that promotion next month, the order still says what the customer was actually given.++## Related++- [Taxes](/developer/core-concepts/taxes) — how tax is worked out+- [Discounts](/developer/core-concepts/discounts) — money off+- [Fees](/developer/core-concepts/fees) — surcharges and duties+- [Carts](/developer/core-concepts/carts) — checkout and completion+- [Orders](/developer/core-concepts/orders) — the placed orderdiff --git a/docs/developer/core-concepts/orders.mdx b/docs/developer/core-concepts/orders.mdxindex cad555f9fb..b2f9f9fb5d 100644--- a/docs/developer/core-concepts/orders.mdx+++ b/docs/developer/core-concepts/orders.mdx@@ -152,7 +152,7 @@ Where admin edits are allowed, totals are re-added from the order's existing row## 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](/developer/core-concepts/taxes-discounts-fees).+Tax, discounts and fees are kept as separate records, so you can ask what tax was charged without picking through a mixed list. See [Order totals](/developer/core-concepts/order-totals).## Eventsdiff --git a/docs/developer/core-concepts/payments.mdx b/docs/developer/core-concepts/payments.mdxindex 1bf4e5ddbd..6db332cea2 100644--- a/docs/developer/core-concepts/payments.mdx+++ b/docs/developer/core-concepts/payments.mdx@@ -1,5 +1,6 @@---title: Payments+description: Taking money — payment methods, payment sessions, saved cards, refunds, and how a payment finishes reliably even when a customer closes the tab.---## Overview@@ -98,7 +99,7 @@ erDiagramCreditCard }o--|| Customer : "belongs to"StoreCredit }o--|| Customer : "belongs to"Refund }o--|| Payment : "belongs to"- Refund }o--|| Reimbursement : "belongs to"+ Refund }o--o| Return : "may come from"```**Key relationships:**@@ -696,22 +697,20 @@ 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+- [Orders](/developer/core-concepts/orders) - Order lifecycle, payment and fulfillment status- [Checkout Customization](/developer/core-concepts/carts) - Customizing the checkout flow- [Events](/developer/core-concepts/events) - Subscribe to payment events-## Key Services+## Two paths to a completed order-| 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. |+A payment can finish in two places, and both have to end at the same result.-Both `Carts::Complete` and `HandleWebhook` are registered in `Spree::Dependencies` and can be replaced with custom implementations:+The customer's browser confirms the payment and your storefront completes the cart. Or the provider's own webhook arrives first — sometimes seconds later, sometimes because the customer closed the tab mid-redirect.-```ruby-# config/initializers/spree.rb-Spree::Dependencies.carts_complete_service = 'MyApp::CustomCartComplete'-Spree::Dependencies.payments_handle_webhook_service = 'MyApp::CustomWebhookHandler'-```+Whichever arrives first completes the order; the other finds the work already done and does nothing. That is what makes a closed tab or a flaky connection recoverable rather than a lost sale with a real charge attached.++<Warning>+Never treat the browser returning from a redirect as proof of payment. The provider's webhook is the authoritative signal — a customer can close the tab, and a browser response can be forged.+</Warning>++Both paths can be replaced if your integration needs different behaviour — see [Dependencies](/developer/customization/dependencies).diff --git a/docs/developer/core-concepts/pricing.mdx b/docs/developer/core-concepts/pricing.mdxindex 12e9b4efe4..b2dfb14116 100644--- a/docs/developer/core-concepts/pricing.mdx+++ b/docs/developer/core-concepts/pricing.mdx@@ -3,8 +3,6 @@ title: Pricingdescription: Prices, Price Lists, Price Rules, and the Pricing Context — Spree's flexible pricing engine for regional, wholesale, volume, and market-based pricing.----import { Since } from '/snippets/since.mdx';-## OverviewSpree's pricing system supports both simple single-currency pricing and advanced multi-currency, rule-based pricing through Price Lists. Every [Variant](/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.@@ -100,7 +98,7 @@ spree api post /prices/bulk_upsert -d '{</CodeGroup>-## Price Lists <Since version="5.3" />+## Price ListsPrice Lists allow you to create different pricing strategies based on various conditions. This enables advanced pricing scenarios like:@@ -173,27 +171,27 @@ spree api patch /price_lists/pl_xxx/activate</CodeGroup>-## Price Rules <Since version="5.3" />+## Price RulesPrice 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](/developer/core-concepts/markets) | Regional pricing across markets |-| **Zone Rule** | Matches based on the customer's geographic zone | Country or state-level pricing |+| **Channel Rule** | Matches based on the [Channel](/developer/core-concepts/channels) the customer is buying through | App-only or in-store 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" />+### Market Rule-The recommended approach for regional pricing when using Markets. Applies the Price List when the customer is in one of the specified markets.+Regional pricing. 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+### Channel Rule-Applies based on the customer's geographic zone. Useful for regional or country-specific pricing when not using Markets.+Applies when the customer is buying through a particular sales channel — a discount that exists only in the mobile app, or a price that only applies at a retail till.### User Rule@@ -217,7 +215,7 @@ Applies based on quantity purchased. Supports `min_quantity` and `max_quantity`Custom Price Rules can be created for specialized pricing logic. See the [Customization Quickstart](/developer/customization/quickstart) for details.</Info>-## Pricing Context <Since version="5.3" />+## Pricing ContextWhen resolving prices, Spree considers the full context of the request:@@ -225,8 +223,8 @@ When resolving prices, Spree considers the full context of the request:|---------|--------|-------------|| Currency | Market or request header | The currency to price in || Market | Customer's country | The [Market](/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 |+| Channel | The API credential in use | The [Channel](/developer/core-concepts/channels) for channel-based rules |+| Customer | Authentication | The signed-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 |@@ -248,7 +246,7 @@ Price Lists are managed in the Admin Panel under **Products → Price Lists**, oEach 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" />+## Price History (EU Omnibus Directive)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.diff --git a/docs/developer/core-concepts/products.mdx b/docs/developer/core-concepts/products.mdxindex 85d43f235f..5472521146 100644--- a/docs/developer/core-concepts/products.mdx+++ b/docs/developer/core-concepts/products.mdx@@ -3,8 +3,6 @@ title: Productsdescription: How Spree models products, variants, option types, images, prices, and categories — the building blocks of every catalog and storefront.----import { Since } from '/snippets/since.mdx';-## OverviewA 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.@@ -18,15 +16,16 @@ Product names, descriptions, slugs, and SEO fields are [translatable](/developer```mermaiderDiagramProduct ||--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"+ Product }o--o{ OptionType : "varies by"+ Product }o--o{ Category : "filed under"+ Product }o--o{ Collection : "grouped into"+ Product ||--o{ Media : "images and video"+ Product }o--|| DeliveryProfile : "ships by"+ Variant ||--o{ Price : "one per currency"+ Variant ||--o{ StockLevel : "stocked per location"+ Variant }o--o{ OptionValue : "identified by"OptionType ||--o{ OptionValue : "has many"- Taxon ||--o{ Classification : "has many"- Taxonomy ||--o{ Taxon : "has many"+ Category ||--o{ Category : "nests under"Product {string name@@ -38,7 +37,7 @@ erDiagramVariant {string sku- boolean is_master+ string barcodedecimal weight}@@ -233,7 +232,7 @@ spree api delete /products/prod_xxxOperating 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>-## Seller submissions <Since version="6.0" />+## Seller submissionsOn a marketplace, a seller lists a product but does not publish one. They submit it, and the marketplace decides. This adds two statuses to the three above — both hidden from the storefront, since only `active` is visible.@@ -644,14 +643,19 @@ See the [Pricing](/developer/core-concepts/pricing) guide for details on Price L## 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**.+There are two ways to group products, and they answer different questions.++**Categories** are a hierarchy — the navigation tree a shopper browses. Clothing contains T-Shirts, which contains Long Sleeve. A product can sit in several categories, and each one has a permalink built from its path.++**Collections** are flat groupings — "Summer 2025", "Best Sellers", "Under $50". A collection can be curated by hand, or defined by rules so products join and leave it on their own as their price, tags or stock change.-For example:-- **Categories** → Clothing → T-Shirts, Dresses-- **Brands** → Nike, Adidas, Puma-- **Collections** → Summer 2025, Best Sellers+| | Categories | Collections |+|---|---|---|+| Shape | Nested tree | Flat list |+| Membership | You assign it | Assigned, or matched by rules |+| Typical use | Site navigation | Merchandising and campaigns |-Products can belong to multiple categories.+A brand is usually best modelled as one or the other rather than as a separate concept — a category if you want it in the navigation tree, a collection if it's a landing page.<CodeGroup>@@ -692,7 +696,19 @@ curl 'https://api.mystore.com/api/v3/store/categories/clothing/shirts/products?lCategory `name` and `description` fields are translatable.</Info>-## Publications and Sales Channels <Since version="5.5" />+Collections work the same way from a storefront's point of view:++```typescript Store SDK+const { data: collections } = await client.collections.list()++const { data: products } = await client.collections.products.list('summer-2025', {+ limit: 12,+})+```++A rule-based collection is defined once and maintains itself — set it to match everything tagged `sale` and under $50, and products appear and disappear as those facts change. Ordering can be manual or by a rule such as newest first.++## Publications and Sales ChannelsA product is visible on a [Channel](/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.diff --git a/docs/developer/core-concepts/promotions.mdx b/docs/developer/core-concepts/promotions.mdxindex cf2f51ad1f..f4a6bf0b0a 100644--- a/docs/developer/core-concepts/promotions.mdx+++ b/docs/developer/core-concepts/promotions.mdx@@ -5,7 +5,9 @@ description: Build percentage and fixed-amount discounts, free shipping, BOGO of## 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](/developer/core-concepts/taxes-discounts-fees#discounts) rows on the order.+A promotion is a campaign: a percentage off, free shipping, or free items in the cart. **Rules** decide when it applies, **actions** decide what it does.++A promotion is a *rule that exists on its own*, set up in advance and lasting across many orders. What lands on any one order is a [Discount](/developer/core-concepts/discounts) — the record of money actually coming off. The promotion is the campaign; the discount is what a particular customer got.```mermaiderDiagram@@ -52,14 +54,13 @@ 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+### When promotions compete-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.+Several promotions can qualify for the same item at once. Spree applies **only the one that saves the customer the most**, and records just that one.-Two things follow from this design:+Losing candidates aren't stored or tracked — they're simply reconsidered on every cart change. So a promotion that loses today can win tomorrow, when the basket changes, without any bookkeeping to keep straight.-- **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.+What an applied promotion leaves behind on the order is a [Discount](/developer/core-concepts/discounts) — a permanent record that survives the promotion being edited or deleted.## Promotion Attributes@@ -112,7 +113,7 @@ You can also [build your own rules](/developer/how-to/custom-promotion) for busiActions define what happens when a promotion applies.-### CreateAdjustment+### Order discount (`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.@@ -120,7 +121,7 @@ A discount on the whole order. The amount is distributed proportionally across t**Use case:** "10% off your order", "$20 off orders over $100".-### CreateItemAdjustments+### Item discount (`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.@@ -128,13 +129,13 @@ A discount on individual line items. Only items that match the promotion's rules**Use case:** "15% off shoes", "Buy 2+ shirts get 10% off each".-### FreeShipping+### Free shipping (`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+### Free items (`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.@@ -253,7 +254,7 @@ Automatic promotions need no customer action at all — they are evaluated on ev## Related Documentation-- [Taxes, Discounts & Fees](/developer/core-concepts/taxes-discounts-fees) — the Discount rows promotions write, and manual discounts+- [Discounts](/developer/core-concepts/discounts) — the 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 ondiff --git a/docs/developer/core-concepts/search-filtering.mdx b/docs/developer/core-concepts/search-filtering.mdxindex bd41d315fc..4aa348ea29 100644--- a/docs/developer/core-concepts/search-filtering.mdx+++ b/docs/developer/core-concepts/search-filtering.mdx@@ -3,13 +3,11 @@ title: Search & Filteringdescription: "Use Ransack-style query parameters to search, filter, sort, and paginate products, taxons, and other resources through the Spree Store API."----import { Since } from '/snippets/since.mdx';-## OverviewSpree 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+- Full-text search across product names, SKUs, and searchable custom fields- Attribute-based filtering (price range, availability, stock status)- Category and taxon filtering- Faceted search with filter counts@@ -294,7 +292,7 @@ curl 'https://api.mystore.com/api/v3/store/products?page=1&limit=24' \See [Querying](/api-reference/store-api/querying) for the full list of filtering, sorting, and pagination options.-## Search Providers <Since version="5.4" />+## Search ProvidersSpree 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.diff --git a/docs/developer/core-concepts/store-credits-gift-cards.mdx b/docs/developer/core-concepts/store-credits-gift-cards.mdxindex 0cbe7e7405..43c895c23f 100644--- a/docs/developer/core-concepts/store-credits-gift-cards.mdx+++ b/docs/developer/core-concepts/store-credits-gift-cards.mdx@@ -3,10 +3,6 @@ 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.----import { Since } from '/snippets/since.mdx';--<Since version="5.1" />-## OverviewSpree provides two stored value mechanisms that customers can use at checkout:diff --git a/docs/developer/core-concepts/taxes-discounts-fees.mdx b/docs/developer/core-concepts/taxes-discounts-fees.mdxdeleted file mode 100644index a52eeddf19..0000000000--- a/docs/developer/core-concepts/taxes-discounts-fees.mdx+++ /dev/null@@ -1,205 +0,0 @@-----title: Taxes, Discounts & Fees-description: How Spree records money added to or taken off an order — separate tax lines, discounts and fees, and the order totals you render in a storefront.------## Overview--An order total is rarely just the sum of item prices. Tax gets added, a promo code takes something off, gift wrapping costs extra. Spree records each of those as its own row, of one of three kinds:--| Kind | Effect | What it is |-|---|---|---|-| **Tax line** | adds | Tax charged on an item, on delivery, or on a fee |-| **Discount** | subtracts | A promotion or a manual reduction |-| **Fee** | adds | A surcharge — handling, gift wrap, cash on delivery |--Keeping them apart means a direct question gets a direct answer. "What tax did we charge on this order?" is one request against tax lines, rather than filtering a mixed list and hoping you caught every case.--```mermaid-erDiagram- Order ||--o{ TaxLine : "has many"- Order ||--o{ Discount : "has many"- Order ||--o{ Fee : "has many"- LineItem ||--o{ TaxLine : "taxed by"- LineItem ||--o{ Discount : "reduced by"- Fulfillment ||--o{ TaxLine : "taxed by"- Fee ||--o{ TaxLine : "taxed by"-- TaxLine {- string label- string rate- boolean included- string amount- }- Discount {- string label- string kind- string code- string amount- }- Fee {- string label- string kind- string amount- }-```--<Note>-Money is sent as a **string** — `"15.99"`, not `15.99`. JavaScript numbers can't represent every decimal exactly, and `0.1 + 0.2` gives `0.30000000000000004`, which is not something you want inside a total. If you need to do arithmetic, use a decimal library or work in whole cents.-</Note>--## Building an order summary--Most storefronts never need the individual rows. The order already carries a total for each kind, so you can render a summary directly:--```typescript-const order = await client.orders.get('or_xxx')--order.display_item_total // "$120.00" items before tax and discounts-order.display_discount_total // "-$12.00" everything taken off-order.display_delivery_total // "$5.00" delivery-order.display_tax_total // "$22.60" all tax-order.display_total // "$135.60" what the customer pays-```--Every total comes in two forms: `total` is the raw value (`"135.60"`) and `display_total` is formatted for the order's currency (`"$135.60"`). Render the `display_` one — it handles the symbol, decimal separator and where the symbol goes.--| Attribute | What it sums |-|---|---|-| `item_total` | Line item prices before tax and discounts |-| `discount_total` | All discounts |-| `tax_total` | All tax |-| `included_tax_total` | Tax already inside displayed prices |-| `additional_tax_total` | Tax added on top |-| `delivery_total` | Delivery charges |-| `total` | What the customer pays |--<Warning>-If you add up a subtotal yourself, include `additional_tax_total` only. `included_tax_total` is **already inside** the item prices — adding it again counts the tax twice. This is the most common mistake when building a European storefront.-</Warning>--## Tax lines--A tax line records one tax charge and what it was charged on.--| Attribute | Description |-|---|---|-| `label` | What the customer sees, e.g. `VAT 20%` |-| `rate` | The rate applied, e.g. `"0.2"` |-| `included` | Whether the tax was already inside the displayed price |-| `amount` / `display_amount` | Tax charged |-| `line_item_id` / `fulfillment_id` / `fee_id` | What was taxed — exactly one is set |-| `tax_rate_id` | The configured rate, when tax came from Spree rather than an outside service |--`included` is the field that trips people up. In most of Europe a €120 price already contains €20 of VAT, so the tax line is there for information — the customer pays €120, not €140. In the US, tax is added at checkout, so the same field is `false` and the amount really is extra.--```typescript Admin SDK-const taxLines = await adminClient.orders.taxLines.list('or_xxx')-```--You never create tax lines yourself. They're written whenever the order total is worked out — see [Taxes](/developer/core-concepts/taxes).--## Discounts--| Attribute | Description |-|---|---|-| `label` | What the customer sees, e.g. `Summer Sale` |-| `kind` | `promotion` or `manual` |-| `code` | The coupon code used, if any |-| `value` / `value_type` | The rule behind it, e.g. `"10"` / `percent`. Accepts a string or a number on write. |-| `amount` / `display_amount` | The reduction, as a negative amount |-| `promotion_id` | The promotion it came from |-| `line_item_id` / `fulfillment_id` | What it reduced |--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>--```typescript Admin SDK-// 10% off a single line item-await adminClient.orders.discounts.create('or_xxx', {- label: 'Goodwill discount',- value: '10',- value_type: 'percent',- line_item_id: 'li_xxx',-})--// A flat amount across the order-await adminClient.orders.discounts.create('or_xxx', {- label: 'Price match',- value: '15.00',- value_type: 'flat',-})-```--```bash cURL-curl -X POST 'https://api.mystore.com/api/v3/admin/orders/or_xxx/discounts' \- -H 'X-Spree-API-Key: sk_xxx' \- -H 'Content-Type: application/json' \- -d '{ "label": "Goodwill discount", "value": 10, "value_type": "percent" }'-```--</CodeGroup>--Only manual discounts can be edited or deleted. Changing one that came from a promotion returns a `422` — those belong to the promotion that created them, and letting an order disagree with its own promotion is how reporting stops adding up.--A discount on the whole order is shared out across the items rather than kept as one lump sum. So if the customer later returns one item, Spree knows how much of the discount belonged to it.--## Fees--| Attribute | Description |-|---|---|-| `label` | What the customer sees, e.g. `Gift wrapping` |-| `kind` | `surcharge`, `handling`, `gift_wrap`, `cod`, `payment`, `duty`, or your own |-| `amount` / `display_amount` | The charge |-| `line_item_id` / `fulfillment_id` | What it applies to — both empty means the whole order |--```typescript Admin SDK-await adminClient.orders.fees.create('or_xxx', {- label: 'Gift wrapping',- kind: 'gift_wrap',- amount: '5.00',- line_item_id: 'li_xxx',-})-```--Fees are always positive, and they're taxable by default — a fee can have its own tax lines. Customs duties are the one exception, described below. To take money off, create a discount instead. That way a refund never has to work out whether a negative fee was a charge or a credit.--### Customs duties--A `duty` fee is the one kind tax is **not** applied to automatically. A customs duty is an import charge levied by the destination country, not a sale that domestic tax applies to, so charging tax on top of it would invent tax the merchant never owed. Where import VAT is charged on a duty, whoever calculates the duty records that tax itself.--A duty also keeps a copy of what it was calculated from — the HS code, the country of origin, the rate — in its `metadata`. Classification on a product can change next month; what the customer was charged must not.--## Where rows attach--Each row points at exactly the thing it applies to:--- **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--Rows also keep a copy of where they came from — the rate and label on a tax line, the code and promotion on a discount. If someone deletes that promotion next month, the order still says what the customer was actually given.--## When totals change--Totals are worked out again whenever something changes on a cart — an item added, an address entered, a code applied. The response to every cart change already includes the new totals, so a follow-up request is never needed:--```typescript-// The returned cart already has updated totals-const cart = await client.carts.items.create(cartId, {- variant_id: 'var_xxx',- quantity: 2,-})--cart.display_total // already correct-```--Once an order is placed, the rows stop being regenerated. Editing a placed order re-adds its existing rows rather than starting from scratch, so today's promotions can't quietly rewrite what a customer agreed to last week.--## Related--- [Taxes](/developer/core-concepts/taxes) — how tax is worked out-- [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 e4ead19eb9..18739a9ead 100644--- a/docs/developer/core-concepts/taxes.mdx+++ b/docs/developer/core-concepts/taxes.mdx@@ -1,169 +1,176 @@---title: Taxes-description: Tax categories, tax rates, zones, and how Spree calculates taxes at checkout+description: How Spree works out tax — tax categories and rates, inclusive versus added-on pricing, and connecting an external tax service.---## 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](/developer/core-concepts/addresses#zones).+Tax is the part of commerce most likely to differ from what you assumed. A US shopper expects `$17.99` on the shelf and a little more at the till. A German shopper expects `€17.99` to be the whole story, VAT already inside it. Both are correct, and a store selling to both has to do both.++Spree handles this by keeping three things separate:++- **What is being sold** — a [tax category](#tax-categories) groups products taxed the same way+- **Where the customer is** — their [market](/developer/core-concepts/markets) and shipping address+- **Who works out the number** — Spree's own rates, or an external tax service++The result of all this is a set of **tax lines** on the order — one per charge, recording what was taxed and at what rate. This page is about how they get their numbers.```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- }+flowchart LR+ Product -->|"has a"| TaxCategory+ Address -->|"determines"| Market+ Market -->|"selects"| Provider["Tax provider"]+ TaxCategory --> Provider+ Provider -->|"writes"| TaxLine["Tax lines on the order"]```-**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](/developer/core-concepts/addresses#zones)-- **Zone** defines geographic regions (countries or states) where taxes apply-- **[Adjustments](/developer/core-concepts/taxes-discounts-fees)** are created on orders/line items to apply taxes+## Tax categories-## Tax Categories+A tax category is how you say "these things are taxed alike". Children's clothing, books and hot food are treated differently from general goods in many countries, and a tax category is where that distinction lives.-Tax categories group products by how they're taxed. Common examples:+Every product carries one. If you don't choose, the default is used.-- **Clothing** — standard tax rate-- **Food** — reduced or exempt rate-- **Digital** — different rules per jurisdiction+| Field | Description | Example |+|---|---|---|+| `name` | What it's called | `Standard`, `Reduced`, `Digital` |+| `is_default` | Used by products that don't pick one | `true` |+| `tax_code` | The code your tax service knows it by | `1257L` |-Each product is assigned a tax category. One category can be set as the default for products that don't have an explicit assignment.+```typescript Admin SDK+const reduced = await adminClient.taxCategories.create({+ name: 'Reduced rate',+ tax_code: '1257L',+})+```-| 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` |+`tax_code` matters once you connect an external service — it is how you tell that service what kind of thing this is, in the vocabulary it already uses.-Manage tax categories via the [Admin API](/api-reference/admin-api/introduction), using the [Admin SDK resource clients](/developer/sdk/admin/resources):+## Tax rates-<CodeGroup>+A tax rate is the number itself, plus where it applies and whether it's already in the price.-```typescript Admin SDK-import { createAdminClient } from '@spree/admin-sdk'+| Field | Description | Example |+|---|---|---|+| `name` | What appears on the invoice | `VAT 20%` |+| `amount` | The rate as a decimal | `0.2` for 20% |+| `included_in_price` | Whether the price already contains it | `true` in the EU |+| `country_code` / `state_code` | Where it applies | `DE`, or `US` + `CA` |+| `tax_category` | What it applies to | `Standard` |-const client = createAdminClient({- baseUrl: 'https://store.example.com',- secretKey: 'sk_xxx',+```typescript Admin SDK+const { data: rates } = await adminClient.taxRates.list()++await adminClient.taxRates.create({+ name: 'VAT 20%',+ amount: '0.2',+ included_in_price: true,+ country_code: 'GB',+ tax_category_id: 'taxcat_xxx',})+```-const clothing = await client.taxCategories.create({- name: 'Clothing',- tax_code: '1257L',- is_default: true,-})+Rates name their country and state by **ISO code**, not by an ID — `DE`, `US` + `CA`. There's no separate region record to create first.-await client.taxCategories.update('taxcat_xxx', { is_default: false })-await client.taxCategories.delete('taxcat_xxx')-```+## Included or added on-```bash CLI-spree api post /tax_categories -d '{"name": "Clothing", "tax_code": "1257L", "is_default": true}'-spree api get /tax_categories-```+`included_in_price` is the single most consequential setting here, so it's worth being precise about what it does.++<Tabs>+ <Tab title="Added on (US style)">+ The shelf price is what the product costs. Tax is worked out at checkout, once the address is known, and added.++ A $17.99 item at 5%:-</CodeGroup>+ | | |+ |---|---|+ | Price shown | **$17.99** |+ | Tax added | $0.90 |+ | Customer pays | **$18.89** |-## Tax Rates+ Set `included_in_price: false`.+ </Tab>+ <Tab title="Included (EU style)">+ The shelf price is the whole price. The tax inside it is shown for information — the customer pays the number they saw.-Tax rates define the percentage charged for a specific tax category within a geographic zone.+ A £17.99 item at 20% VAT:-| 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` |+ | | |+ |---|---|+ | Price shown | **£17.99** |+ | VAT inside it | £3.00 |+ | Customer pays | **£17.99** |-## Tax Types+ Set `included_in_price: true`.+ </Tab>+</Tabs>-### Sales Tax (tax-exclusive)+<Warning>+When building an order summary, add `additional_tax_total` only. `included_tax_total` is **already inside** the item prices — adding it counts the tax twice. This is the most common bug in a European storefront.+</Warning>-Common in the United States. The displayed price does **not** include tax — tax is added at checkout based on the shipping address.+Because prices are shown before anyone knows where the shopper lives, each [Market](/developer/core-concepts/markets) declares whether its prices are quoted with tax included. That's what lets a catalogue page show honest prices to a German visitor and a US visitor at the same time.-**Example:** A $17.99 item with 5% sales tax:-- Displayed price: **$17.99**-- Tax at checkout: **$0.90**-- Order total: **$18.89**+## Tax lines-### Value Added Tax / VAT (tax-inclusive)+Whatever works out the tax, the record is the same: a tax line per charge, saying what was taxed and how.-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.+| Attribute | Description |+|---|---|+| `label` | What the customer sees — `VAT 20%` |+| `rate` | The rate applied — `"0.2"` |+| `included` | Whether the tax was already inside the displayed price |+| `amount` / `display_amount` | The tax charged |+| `line_item_id` / `fulfillment_id` / `fee_id` | What was taxed — exactly one is set |-**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**+```typescript Admin SDK+const { data: taxLines } = await adminClient.orders.taxLines.list('or_xxx')+```++Tax lines attach to a line item, a [fulfillment](/developer/core-concepts/fulfillments), or a [fee](/developer/core-concepts/fees) — so tax on goods and tax on delivery stay separately visible, which is what a tax return needs.-<Info>-The `tax_inclusive` setting on [Markets](/developer/core-concepts/markets) controls whether prices are displayed with or without tax for each geographic region.-</Info>+Each line also keeps its own copy of the rate and label. If someone edits that tax rate next year, the order still says what the customer was actually charged.-## Default Tax Zone+You never create tax lines yourself; they're written whenever the total is worked out.-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.+## When tax is worked out-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 is recalculated whenever the answer could have changed — an item added, an address entered, a delivery option chosen. Every one of those requests returns the updated cart, so a storefront never needs a separate "refresh the tax" call.-## Tax Calculation at Checkout+<Steps>+ <Step title="Before an address is known">+ Prices are shown using the market's tax treatment. For an inclusive market the displayed price is the real one; for an added-on market tax simply hasn't been worked out yet.+ </Step>+ <Step title="Once the shipping address is entered">+ The address decides the real rate. Tax lines are written against each item, the delivery charge, and any taxable fee.+ </Step>+ <Step title="At completion">+ Whatever the tax is at that moment is what's charged, and the order keeps it. A rate change next month does not rewrite an order from last month.+ </Step>+</Steps>-During checkout, taxes are calculated based on the shipping address:+## Connecting a tax service-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/taxes-discounts-fees) are created on line items-4. The order total is updated+Spree's built-in rate tables are fine when the rules are simple — one country, or a handful of clearly-defined rates. They become a liability where the rules are not: US sales tax varies by city and changes constantly, and cross-border EU VAT has thresholds that shift with your turnover.-<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>+For those, connect a real tax service. **The provider is chosen per [Market](/developer/core-concepts/markets)**, which means one store can use its own rates in a simple market and an external service in a complicated one.-## Managing Taxes+```typescript Admin SDK+const { data: providers } = await adminClient.taxProviders.list()+```-Tax categories and rates are managed in the Admin Panel under **Settings → Taxes**, or via the Admin API.+A provider declares up front what it cannot do — no US local tax, no reverse charge — so the dashboard can warn a merchant who pairs it with a market that needs it, rather than quietly under-collecting.-### Common Configurations+Whichever provider is in use, the result is the same: tax lines on the order, in the same shape. Your storefront code doesn't change.-**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`+## Tax-exempt customers-**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+Business customers are often exempt, and the paperwork is real. Spree records a customer's or company's **tax identifier** — a VAT number, an ABN — and can validate it. Companies can also hold exemption certificates, scoped to the country or state that issued them.-**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+Exemption is decided when tax is worked out, not stored as a flag on the customer, so an expired certificate stops applying by itself. See [Companies & Catalogs](/developer/core-concepts/companies-and-catalogs).-## Related Documentation+## Related-- [Markets](/developer/core-concepts/markets) — Tax-inclusive pricing per market-- [Addresses](/developer/core-concepts/addresses) — Zones and address-based taxation-- [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 jurisdictions+- [Order totals](/developer/core-concepts/order-totals) — how tax rolls into what a customer pays+- [Markets](/developer/core-concepts/markets) — where tax treatment and provider are chosen+- [Addresses](/developer/core-concepts/addresses) — what determines the rate+- [Companies & Catalogs](/developer/core-concepts/companies-and-catalogs) — B2B tax identifiers and exemptionsdiff --git a/docs/developer/core-concepts/translations.mdx b/docs/developer/core-concepts/translations.mdxindex 6f91596c77..0ded707915 100644--- a/docs/developer/core-concepts/translations.mdx+++ b/docs/developer/core-concepts/translations.mdx@@ -1,98 +1,79 @@---title: Translations-description: Translate Spree products, taxons, and other store content into multiple languages using Mobility-backed translations and locale-aware APIs.+description: Selling in more than one language — translating product content, and translating the interface around it.---## Overview-Spree supports two types of translations:+Two different things need translating, and they're handled separately because they belong to different people.-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)+**Your content** — product names, descriptions, category names — is written by whoever runs the store. Spree stores a version of each field per language.-For configuring which locales and currencies are available in your store, see [Markets](/developer/core-concepts/markets). Markets control locale and currency assignment per geographic region.+**The interface** — button labels, error messages, email wording — is written by Spree, and is already translated into dozens of languages by the community.-## Resource Translations+<Info>+Which languages a region gets is decided by its [Market](/developer/core-concepts/markets). A market sets the default locale alongside the currency, so a visitor from France lands on French prices and French copy without choosing anything.+</Info>++## Translating content-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`.+Every translatable record keeps one row per language, so a product genuinely has a French name rather than a French name pasted over the English one.```mermaiderDiagram- Product ||--o{ ProductTranslation : "has many"- Taxon ||--o{ TaxonTranslation : "has many"- Store ||--o{ StoreTranslation : "has many"+ Product ||--o{ ProductTranslation : "one per locale"Product {- string id PKstring status+ string sku}-ProductTranslation {- string id PK- string product_id FKstring localestring name- text description+ string descriptionstring slugstring meta_title- string meta_description- }-- TaxonTranslation {- string id PK- string taxon_id FK- string locale- string name- text description- string permalink}```-### Translatable Fields+### What can be translated++| Resource | Fields |+|---|---|+| Product | `name`, `description`, `slug`, `meta_title`, `meta_description` |+| Category | `name`, `description`, `permalink` |+| Collection | `name`, `description`, `permalink` |+| Product type | `name` |+| Option type | `presentation` |+| Option value | `presentation` |+| Store | `name`, `seo_title`, `meta_description`, `meta_keywords`, and support contact details |+| Policy | `name`, `body` |+| Seller | `name`, `about` |-| 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` |+Note that **slugs are translated too**. A French page can live at `/produits/sac-spree` rather than at the English slug with French words on it — which is what search engines actually reward. See [Slugs](/developer/core-concepts/slugs#internationalization).-### Store API+## Reading translated content-To retrieve translated content, pass the locale via the [`X-Spree-Locale` header](/api-reference/store-api/localization) or the SDK `locale` option:+Ask for a locale and you get that language back. Nothing else about the request changes:<CodeGroup>```typescript Store SDK-// Fetch product in French-const product = await client.products.get('spree-tote', {}, {- locale: 'fr',-})+const product = await client.products.get('spree-tote', {}, { locale: 'fr' })product.name // "Sac Spree"-product.description // "Un sac fourre-tout élégant..."+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',-})+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.+// The Admin API resolves by ID only — slugs are not accepted hereconst product = await adminClient.products.get('prod_86Rf07xd4z', {}, { locale: 'fr' })--const { data: categories } = await adminClient.categories.list({}, { locale: 'de' })``````bash cURL-# Fetch product in Frenchcurl 'https://api.mystore.com/api/v3/store/products/spree-tote' \-H 'X-Spree-API-Key: pk_xxx' \-H 'X-Spree-Locale: fr'@@ -100,41 +81,57 @@ curl 'https://api.mystore.com/api/v3/store/products/spree-tote' \</CodeGroup>-Slugs are also localized — a product can have different slugs per locale. See [Slugs](/developer/core-concepts/slugs#internationalization) for details.+If a field has no translation for the requested locale, you get the default-language value rather than an empty string — a half-translated catalogue still renders as a usable page.++<Note>+Responses vary by locale, so if you cache them, include the locale in the cache key. Spree sets `Vary` headers for you, which is enough for a CDN but not for a hand-rolled in-memory cache.+</Note>++## Writing translations-### Managing Translations+Merchants translate in the dashboard, switching locale on the record they're editing. For bulk work — handing a catalogue to a translation agency — export to CSV, translate, and import it back.-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 written through the Admin API, which is what you'd use to sync from an external translation service:-Translations can also be [managed via the Admin API](/developer/sdk/admin/quickstart).+```typescript Admin SDK+await adminClient.products.update('prod_xxx', {+ translations: {+ fr: { name: 'Sac Spree', description: 'Un sac fourre-tout élégant…' },+ de: { name: 'Spree Tasche' },+ },+})++// Which resources and fields accept translations+const { data: resources } = await adminClient.translatableResources.list()+```-## UI Translations+Asking the API which resources are translatable means a translation tool doesn't need a hardcoded list that goes stale.-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.+## Translating the interface-To install UI translations:+Spree's own strings — everything in the dashboard and in transactional emails — come from a community-maintained project covering 40+ languages.<CodeGroup>-```bash Spree CLI (Docker)+```bash Spree CLIspree bundle add spree_i18n```-```bash Without Spree CLI+```bash Bundlerbundle add spree_i18n```</CodeGroup>-Once installed, all translation files are available automatically — no need to copy any files.+That's the whole installation. Locales are picked up automatically; nothing needs copying into your app.<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).+See the [supported locales](https://github.com/spree-contrib/spree_i18n/tree/main/config/locales) in the Spree I18n repository. Contributions are welcome if yours is incomplete.</Info>-## Related Documentation+## Related-- [Markets](/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](/developer/core-concepts/slugs) — Localized slugs and URL identifiers-- [Products](/developer/core-concepts/products) — Product translations+- [Markets](/developer/core-concepts/markets) — which locale and currency a region gets+- [Slugs](/developer/core-concepts/slugs) — localized URLs+- [Custom Fields](/developer/core-concepts/metafields) — translating your own fields+- [Localization](/api-reference/store-api/localization) — the locale, currency and country headersdiff --git a/docs/developer/core-concepts/webhooks.mdx b/docs/developer/core-concepts/webhooks.mdxindex e3302c65b1..b73aaf3fd6 100644--- a/docs/developer/core-concepts/webhooks.mdx+++ b/docs/developer/core-concepts/webhooks.mdx@@ -3,10 +3,6 @@ title: Webhooksdescription: Send real-time HTTP notifications to external services when events occur in your store.----import { Since } from '/snippets/since.mdx';--<Since version="5.3" />-## OverviewWebhooks 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.@@ -45,7 +41,7 @@ flowchart LRend```-1. An event is published (e.g., `order.completed`)+1. An event is published (e.g., `order.placed`)2. The `WebhookEventSubscriber` receives all events3. It finds active webhook endpoints subscribed to that event4. For each endpoint, it creates a `WebhookDelivery` record and queues a job@@ -113,13 +109,13 @@ The `subscriptions` attribute controls which events trigger webhooks to this end```typescript Admin SDKawait client.webhookEndpoints.update('whe_xxx', {- subscriptions: ['order.completed', 'order.canceled'],+ subscriptions: ['order.placed', 'order.canceled'],})``````bash CLIspree api patch /webhook_endpoints/whe_xxx \- -d '{"subscriptions": ["order.completed", "order.canceled"]}'+ -d '{"subscriptions": ["order.placed", "order.canceled"]}'```</CodeGroup>@@ -128,7 +124,7 @@ The `subscriptions` array accepts exact event names and wildcard patterns:| `subscriptions` value | Receives ||---|---|-| `['order.completed', 'order.canceled']` | Only those two events |+| `['order.placed', 'order.canceled']` | Only those two events || `['order.*']` | All order events || `['*.created']` | All creation events || `['order.*', 'payment.*', 'shipment.shipped']` | Multiple patterns |@@ -141,7 +137,7 @@ Each webhook delivery sends a JSON payload with the following structure. The `da```json{"id": "550e8400-e29b-41d4-a716-446655440000",- "name": "order.completed",+ "name": "order.placed","created_at": "2025-01-15T10:30:00Z","data": {"id": "or_m3Rp9wXz",@@ -165,7 +161,7 @@ Each webhook delivery sends a JSON payload with the following structure. The `da| Field | Description ||-------|-------------|| `id` | Unique UUID for this event |-| `name` | Event name (e.g., `order.completed`) |+| `name` | Event name (e.g., `order.placed`) || `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 |@@ -182,7 +178,7 @@ Each webhook request includes these headers:|--------|-------------|| `Content-Type` | `application/json` || `User-Agent` | `Spree-Webhooks/1.0` |-| `X-Spree-Webhook-Event` | Event name (e.g., `order.completed`) |+| `X-Spree-Webhook-Event` | Event name (e.g., `order.placed`) || `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` |@@ -234,7 +230,7 @@ class WebhooksController < ApplicationControllerevent = JSON.parse(request.body.read)case event['name']- when 'order.completed'+ when 'order.placed'handle_order_completed(event['data'])when 'product.updated'handle_product_updated(event['data'])@@ -279,7 +275,7 @@ 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 get /webhook_endpoints/whe_xxx/deliveries -q event_name_eq=order.placedspree api post /webhook_endpoints/whe_xxx/deliveries/whd_xxx/redeliver```@@ -301,24 +297,9 @@ spree api post /webhook_endpoints/whe_xxx/deliveries/whd_xxx/redeliver## Configuration-### Enabling/Disabling Webhooks--Webhooks are enabled by default. To disable globally:+Webhooks are on by default and can be switched off installation-wide.-```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)-```+SSL certificates are verified in production, and not in development — so you can point an endpoint at a local tunnel with a self-signed certificate while building. Both are configurable if your environment needs something different.## Available Events@@ -328,14 +309,16 @@ 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`) |+| `order.placed` | A customer completed checkout |+| `order.paid` | The order is fully paid |+| `order.canceled` | The order was canceled |+| `order.shipped` | Everything on the order has shipped |+| `fulfillment.shipped` | One parcel went out |+| `payment.completed` | A payment succeeded |+| `product.created` / `product.updated` | Catalog changes |+| `product.out_of_stock` / `product.back_in_stock` | Availability flipped |+| `customer.created` | A new customer registered |+| `return.received` | A return arrived |## Testing Webhooks@@ -369,24 +352,6 @@ spree api post /webhook_endpoints/whe_xxx/send_test`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}>@@ -411,10 +376,10 @@ end### 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+1. Check that webhooks are enabled installation-wide+2. Verify the endpoint is marked active+3. Confirm the endpoint actually subscribes to the event you expect+4. Check the event belongs to the same store as the endpoint### Signature Verification Failingdiff --git a/docs/developer/how-to/custom-promotion.mdx b/docs/developer/how-to/custom-promotion.mdxindex 62ec4fcb25..87bf5aa0d2 100644--- a/docs/developer/how-to/custom-promotion.mdx+++ b/docs/developer/how-to/custom-promotion.mdx@@ -8,7 +8,7 @@ description: Step-by-step guide to creating custom promotion rules, discount actSpree's promotion system has three extension points:- **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+- **Actions** — what an applied promotion does, usually writing [Discount](/developer/core-concepts/discounts) rows- **Adjusters** — for discounts and fees that aren't promotions at all (loyalty pricing, gift wrap fees, payment surcharges)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.@@ -242,7 +242,7 @@ Like rules, registered actions surface automatically in the dashboard's promotio## 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.+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](/developer/core-concepts/fees) or [Discount](/developer/core-concepts/discounts) rows.```ruby app/models/my_app/adjusters/gift_wrap.rbmodule MyApp@@ -333,6 +333,6 @@ end## Related Documentation- [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+- [Discounts](/developer/core-concepts/discounts) and [Fees](/developer/core-concepts/fees) — the 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/docs.json b/docs/docs.jsonindex df4a7821de..f5fbb854f4 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -32,6 +32,10 @@"library": "lucide"},"redirects": [+ {+ "source": "/developer/core-concepts/taxes-discounts-fees",+ "destination": "/developer/core-concepts/order-totals"+ },{"source": "/developer/storefront/images","destination": "/developer/core-concepts/media"@@ -499,9 +503,11 @@"pages": ["developer/core-concepts/carts","developer/core-concepts/orders",+ "developer/core-concepts/order-totals","developer/core-concepts/payments","developer/core-concepts/taxes",- "developer/core-concepts/taxes-discounts-fees",+ "developer/core-concepts/discounts",+ "developer/core-concepts/fees","developer/core-concepts/promotions","developer/core-concepts/store-credits-gift-cards"]@@ -1867,9 +1873,13 @@"group": "Cart & Checkout","icon": "shopping-cart","pages": [+ "developer/core-concepts/carts","developer/core-concepts/orders",+ "developer/core-concepts/order-totals","developer/core-concepts/payments","developer/core-concepts/taxes",+ "developer/core-concepts/discounts",+ "developer/core-concepts/fees","developer/core-concepts/promotions","developer/core-concepts/store-credits-gift-cards"]@@ -1878,9 +1888,9 @@"group": "Fulfillment","icon": "truck","pages": [- "developer/core-concepts/shipments",+ "developer/core-concepts/fulfillments",+ "developer/core-concepts/returns-exchanges-claims","developer/core-concepts/addresses",- "developer/core-concepts/adjustments","developer/core-concepts/calculators"]},@@ -1893,7 +1903,6 @@"developer/core-concepts/translations","developer/core-concepts/slugs","developer/core-concepts/metafields",- "developer/core-concepts/reports","developer/core-concepts/imports-exports"]}