Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

[Skip CI] documentation update

Damian Legawiec7ffdfff0b605
diff --git a/core/lib/tasks/products.rake b/core/lib/tasks/products.rake
index 2daa75a3aa..7b1272a14e 100644
--- a/core/lib/tasks/products.rake
+++ b/core/lib/tasks/products.rake
@@ -18,7 +18,7 @@ namespace :spree do
end
desc 'Enqueue background jobs to populate product metrics for all store products'
- task populate: :environment do
+ task populate_metrics: :environment do
total_count = 0
Spree::StoreProduct.in_batches(of: 100) do |batch|
diff --git a/core/lib/tasks/taxons.rake b/core/lib/tasks/taxons.rake
index 7cd53bd6a8..c89a41deef 100644
--- a/core/lib/tasks/taxons.rake
+++ b/core/lib/tasks/taxons.rake
@@ -1,21 +1,19 @@
namespace :spree do
namespace :taxons do
- desc 'Reset children_count counter cache on taxons'
- task reset_children_count: :environment do |_t, _args|
- puts 'Resetting children_count counter cache...'
- Spree::Taxon.in_batches.update_all(
- "children_count = (SELECT COUNT(*) FROM spree_taxons AS children WHERE children.parent_id = spree_taxons.id)"
- )
- puts 'Done!'
- end
+ desc 'Reset counter caches (children_count, classification_count) on taxons'
+ task reset_counter_caches: :environment do |_t, _args|
+ puts 'Resetting taxon counter caches...'
+
+ Spree::Taxon.find_each do |taxon|
+ taxon.update_columns(
+ children_count: taxon.children.count,
+ classification_count: taxon.classifications.count,
+ updated_at: Time.current
+ )
+ print '.'
+ end
- desc 'Reset classification_count counter cache on taxons'
- task reset_classification_count: :environment do |_t, _args|
- puts 'Resetting classification_count counter cache...'
- Spree::Taxon.in_batches.update_all(
- "classification_count = (SELECT COUNT(*) FROM spree_products_taxons WHERE spree_products_taxons.taxon_id = spree_taxons.id)"
- )
- puts 'Done!'
+ puts "\nDone!"
end
end
end
diff --git a/docs/developer/admin/custom-javascript.mdx b/docs/developer/admin/custom-javascript.mdx
index a2c5844ba8..f6f9e1b203 100644
--- a/docs/developer/admin/custom-javascript.mdx
+++ b/docs/developer/admin/custom-javascript.mdx
@@ -97,7 +97,9 @@ If you need to add a small piece of JavaScript code (eg. tracking, marketing, an
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.admin.partials.head << 'spree/admin/shared/my_tracking_code'
+ Rails.application.config.after_initialize do
+ Spree.admin.partials.head << 'spree/admin/shared/my_tracking_code'
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
diff --git a/docs/developer/admin/extending-ui.mdx b/docs/developer/admin/extending-ui.mdx
index 3a55a35079..eb60676300 100644
--- a/docs/developer/admin/extending-ui.mdx
+++ b/docs/developer/admin/extending-ui.mdx
@@ -36,7 +36,9 @@ Let's say you want to add a new footer to the admin dashboard. You'll need to ge
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.admin.partials.body_end << 'spree/admin/shared/additional_footer'
+ Rails.application.config.after_initialize do
+ Spree.admin.partials.body_end << 'spree/admin/shared/additional_footer'
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
@@ -1776,3 +1778,10 @@ Here's a list of all places you can inject your custom code:
```
</Accordion>
</AccordionGroup>
+
+## Related Documentation
+
+- [Admin Navigation](/developer/admin/navigation) - Add custom menu items to the admin
+- [Admin Tables](/developer/admin/tables) - Customize admin list views
+- [Form Builder](/developer/admin/form-builder) - Build admin forms with Spree's form helpers
+- [Customization Quickstart](/developer/customization/quickstart) - Overview of all customization options
diff --git a/docs/developer/admin/navigation.mdx b/docs/developer/admin/navigation.mdx
index 5ceb6a1e4e..af54aa6d39 100644
--- a/docs/developer/admin/navigation.mdx
+++ b/docs/developer/admin/navigation.mdx
@@ -559,7 +559,9 @@ Add this to your `config/initializers/spree.rb`:
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.admin.navigation.store << 'spree/admin/shared/inventory_nav'
+ Rails.application.config.after_initialize do
+ Spree.admin.navigation.store << 'spree/admin/shared/inventory_nav'
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
@@ -695,7 +697,9 @@ To add an item to an existing submenu (e.g., Products), use the appropriate inje
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.admin.navigation.store_products << 'spree/admin/shared/custom_products_nav'
+ Rails.application.config.after_initialize do
+ Spree.admin.navigation.store_products << 'spree/admin/shared/custom_products_nav'
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
@@ -721,7 +725,9 @@ Register with:
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.admin.navigation.settings << 'spree/admin/shared/custom_settings_nav'
+ Rails.application.config.after_initialize do
+ Spree.admin.navigation.settings << 'spree/admin/shared/custom_settings_nav'
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
@@ -819,5 +825,7 @@ Register with:
### Related Documentation
- [Extending Admin UI](/developer/admin/extending-ui) - Learn about other UI injection points
+- [Admin Tables](/developer/admin/tables) - Customize admin list views
- [Helper Methods](/developer/admin/helper-methods) - Explore other admin helper methods
- [Permissions](/developer/customization/permissions) - Understand the authorization system
+- [Customization Quickstart](/developer/customization/quickstart) - Overview of all customization options
diff --git a/docs/developer/admin/tables.mdx b/docs/developer/admin/tables.mdx
index 7db604f9b6..4578c23a45 100644
--- a/docs/developer/admin/tables.mdx
+++ b/docs/developer/admin/tables.mdx
@@ -564,3 +564,10 @@ Spree.admin.tables.get(:products)
# Shorthand access
Spree.admin.tables.products
```
+
+## Related Documentation
+
+- [Admin Navigation](/developer/admin/navigation) - Add custom menu items to the admin
+- [Extending Admin UI](/developer/admin/extending-ui) - Inject partials into admin pages
+- [Search & Filtering](/developer/core-concepts/search-filtering) - Add searchable/filterable fields
+- [Customization Quickstart](/developer/customization/quickstart) - Overview of all customization options
diff --git a/docs/developer/contributing/creating-an-extension.mdx b/docs/developer/contributing/creating-an-extension.mdx
index 17e0883106..02d5d588e8 100644
--- a/docs/developer/contributing/creating-an-extension.mdx
+++ b/docs/developer/contributing/creating-an-extension.mdx
@@ -7,6 +7,10 @@ description: Learn how to create a Spree extension.
[Spree Extensions](/developer/customization/extensions) are a way to add new functionality to your Spree store. They are a great way to extend the functionality of Spree and add new features. You can share them with Spree community on Github so anyone can use them, contribute back and share your improvements.
+<Info>
+ This tutorial uses decorators for extending Spree models. For extensions that need to react to events (sync with external services, send notifications, etc.), consider using [Events subscribers](/developer/core-concepts/events) instead - they're easier to test and maintain. See [Customization Quickstart](/developer/customization/quickstart) for guidance on choosing the right approach.
+</Info>
+
## Getting Started
Let's build a simple extension. Suppose we want the ability to mark certain products as being on sale. We'd like to be able to set a sale price on a product and show products that are on sale on a separate products page. This is a great example of how an extension can be used to build on the solid Spree foundation.
@@ -217,3 +221,40 @@ These specs test that the `price_in` method we overrode in our `VariantDecorator
## Summary
In this tutorial, you learned how to both install extensions and create your own. A lot of core Spree development concepts were covered and you gained exposure to some of the Spree internals.
+
+## Alternative Approaches
+
+While this tutorial uses decorators to extend Spree's core behavior, modern Spree provides additional patterns that may be more appropriate depending on your use case:
+
+| Use Case | Recommended Approach |
+|----------|---------------------|
+| Structural changes (associations, validations) | Decorators (as shown in this tutorial) |
+| React to model changes | [Events subscribers](/developer/core-concepts/events) |
+| External service integration | [Webhooks](/developer/core-concepts/webhooks) |
+| Replace core services | [Dependencies injection](/developer/customization/dependencies) |
+| Add admin UI elements | [Admin Partials](/developer/admin/extending-ui) |
+| Add admin menu items | [Admin Navigation](/developer/admin/navigation) |
+
+For example, if your extension needs to sync data with an external service when products are updated, use an Events subscriber instead of a decorator callback:
+
+```ruby app/subscribers/my_extension/product_sync_subscriber.rb
+module MyExtension
+ class ProductSyncSubscriber < Spree::Subscriber
+ subscribes_to 'product.updated'
+
+ def handle(event)
+ product = Spree::Product.find_by(id: event.payload['id'])
+ return unless product
+
+ ExternalService.sync(product)
+ end
+ end
+end
+```
+
+## Related Documentation
+
+- [Events](/developer/core-concepts/events) - Subscribe to Spree events
+- [Webhooks](/developer/core-concepts/webhooks) - HTTP callbacks for external integrations
+- [Dependencies](/developer/customization/dependencies) - Replace core services
+- [Customization Quickstart](/developer/customization/quickstart) - Choose the right approach
diff --git a/docs/developer/core-concepts/addresses.mdx b/docs/developer/core-concepts/addresses.mdx
index 9a96eae9e4..934838f849 100644
--- a/docs/developer/core-concepts/addresses.mdx
+++ b/docs/developer/core-concepts/addresses.mdx
@@ -2,6 +2,73 @@
title: Addresses
---
+### Address Model Diagram
+
+```mermaid
+erDiagram
+ Address {
+ string firstname
+ string lastname
+ string address1
+ string address2
+ string city
+ string zipcode
+ string phone
+ string state_name
+ string company
+ string label
+ }
+
+ Country {
+ string name
+ string iso
+ string iso3
+ string iso_name
+ integer numcode
+ }
+
+ State {
+ string name
+ string abbr
+ }
+
+ Zone {
+ string name
+ string description
+ boolean default_tax
+ string kind
+ }
+
+ ZoneMember {
+ string zoneable_type
+ }
+
+ User {
+ string email
+ integer ship_address_id
+ integer bill_address_id
+ }
+
+ Address }o--|| Country : "belongs to"
+ Address }o--o| State : "belongs to"
+ Address }o--o| User : "belongs to"
+ User ||--o{ Address : "has many"
+ User }o--o| Address : "default ship"
+ User }o--o| Address : "default bill"
+ Order }o--|| Address : "ship_address"
+ Order }o--|| Address : "bill_address"
+ Country ||--o{ State : "has many"
+ Zone ||--o{ ZoneMember : "has many"
+ ZoneMember }o--o| Country : "member"
+ ZoneMember }o--o| State : "member"
+```
+
+**Key relationships:**
+- **Address** stores shipping/billing information for [Orders](/developer/core-concepts/orders) and Users
+- **Country** and **State** provide geographic data for addresses
+- **Zone** groups countries or states for [tax](/developer/core-concepts/taxes) and [shipping](/developer/core-concepts/shipments) rules
+- **Zone Members** link zones to their geographic components
+
The `Spree::Address` model is used to track address information, mainly for orders. Address information can also be tied to the `Spree.user_class` which by default is `Spree::User` ([More on Users](users)).
Addresses have the following attributes:
@@ -46,7 +113,7 @@ When an order's address is linked to a country or a state, that can ultimately a
A zone is comprised of many different "zone members", which can either be a set of countries or a set of states.
-Every order has a "tax zone", which indicates if a user should or shouldn't be taxed when placing an order. For more information, please see the [Taxation](taxation) guide.
+Every order has a "tax zone", which indicates if a user should or shouldn't be taxed when placing an order. For more information, please see the [Taxes](taxes) guide.
In addition to tax zones, orders also have shipping methods. These are provided to the user based on their address information, and once selected lock in how an order is going to be shipped to that user. For more information, please see the [Shipments](shipments) guide.
@@ -69,3 +136,10 @@ Country data is provided by [Carmen gem](https://github.com/carmen-ruby/carmen)
States, or regions, provinces, or districts are used to scope address data slightly more than country. States are useful for tax purposes, as different states in a country may impose different tax rates on different products. In addition to this, different states may cause different tax rates and shipping methods to be used for an order, similar to how countries affect it also.
+## Related Documentation
+
+- [Users](/developer/core-concepts/users) - User accounts and address books
+- [Taxes](/developer/core-concepts/taxes) - How addresses affect taxation
+- [Shipments](/developer/core-concepts/shipments) - How addresses affect shipping
+- [Orders](/developer/core-concepts/orders) - Order billing and shipping addresses
+
diff --git a/docs/developer/core-concepts/adjustments.mdx b/docs/developer/core-concepts/adjustments.mdx
index 66e044bc55..844de0636d 100644
--- a/docs/developer/core-concepts/adjustments.mdx
+++ b/docs/developer/core-concepts/adjustments.mdx
@@ -4,6 +4,64 @@ title: Adjustments
## Overview
+### Adjustment Model Diagram
+
+```mermaid
+erDiagram
+ Adjustment {
+ decimal amount
+ string label
+ boolean eligible
+ boolean mandatory
+ string state
+ boolean included
+ string source_type
+ string adjustable_type
+ }
+
+ Order {
+ string number
+ decimal adjustment_total
+ decimal total
+ }
+
+ LineItem {
+ integer quantity
+ decimal price
+ decimal adjustment_total
+ }
+
+ Shipment {
+ string number
+ decimal cost
+ decimal adjustment_total
+ }
+
+ TaxRate {
+ string name
+ decimal amount
+ boolean included_in_price
+ }
+
+ PromotionAction {
+ string type
+ }
+
+ Order ||--o{ Adjustment : "has many"
+ Order ||--o{ LineItem : "has many"
+ Order ||--o{ Shipment : "has many"
+ LineItem ||--o{ Adjustment : "has many"
+ Shipment ||--o{ Adjustment : "has many"
+ TaxRate ||--o{ Adjustment : "creates"
+ PromotionAction ||--o{ Adjustment : "creates"
+```
+
+**Key relationships:**
+- **Adjustment** modifies prices on orders, line items, or shipments
+- **Source** is where the adjustment comes from ([Tax Rate](/developer/core-concepts/taxes) or [Promotion Action](/developer/core-concepts/promotions))
+- **Adjustable** is what's being adjusted (Order, LineItem, or Shipment)
+- Positive amounts are charges, negative amounts are credits
+
An `Adjustment` object tracks an adjustment to the price of an [Order](orders), an order's [Line Item](orders#line-items), or an order's [Shipments](shipments) within a Spree Commerce storefront.
Adjustments can be either positive or negative. Adjustments with a positive value are sometimes referred to as "charges" while adjustments with a negative value are sometimes referred to as "credits." These are just terms of convenience since there is only one `Spree::Adjustment` model in a storefront which handles this by allowing either positive or negative values.
@@ -135,22 +193,33 @@ Next you need to add the class to spree `Spree.adjusters` so it is included when
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.adjusters = [
- Spree::Adjustable::Adjuster::MyAdjuster,
- Spree::Adjustable::Adjuster::Promotion,
- Spree::Adjustable::Adjuster::Tax
- ]
+ Rails.application.config.after_initialize do
+ Spree.adjusters = [
+ Spree::Adjustable::Adjuster::MyAdjuster,
+ Spree::Adjustable::Adjuster::Promotion,
+ Spree::Adjustable::Adjuster::Tax
+ ]
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
```ruby config/initializers/spree.rb
- Rails.application.config.spree.adjusters = [
- Spree::Adjustable::Adjuster::MyAdjuster,
- Spree::Adjustable::Adjuster::Promotion,
- Spree::Adjustable::Adjuster::Tax
- ]
+ Rails.application.config.after_initialize do
+ Rails.application.config.spree.adjusters = [
+ Spree::Adjustable::Adjuster::MyAdjuster,
+ Spree::Adjustable::Adjuster::Promotion,
+ Spree::Adjustable::Adjuster::Tax
+ ]
+ end
```
</Tab>
</Tabs>
-That's it! Your custom adjuster is ready to go.
\ No newline at end of file
+That's it! Your custom adjuster is ready to go.
+
+## Related Documentation
+
+- [Promotions](/developer/core-concepts/promotions) - Promotion-based adjustments
+- [Taxes](/developer/core-concepts/taxes) - Tax adjustments
+- [Shipments](/developer/core-concepts/shipments) - Shipping adjustments
+- [Orders](/developer/core-concepts/orders) - How adjustments affect order totals
\ No newline at end of file
diff --git a/docs/developer/core-concepts/architecture.mdx b/docs/developer/core-concepts/architecture.mdx
index 5530ef5e2a..e11c2ce3c4 100644
--- a/docs/developer/core-concepts/architecture.mdx
+++ b/docs/developer/core-concepts/architecture.mdx
@@ -1,42 +1,177 @@
---
title: Architecture
-description: Learn about the Spree architecture
+description: Understand how Spree's core models and systems work together
---
-Spree is a modular full-stack platform that can be used to build a wide range of e-commerce applications. It includes:
-
-<CardGroup>
- <Card title="Core" icon="code">
- <p>Core is the foundation of Spree, such as models, services, and the backend logic necessary to run an e-commerce business.</p>
- </Card>
- <Card title="Admin Dashboard" icon="gauge">
- <p>The Admin Dashboard is the control center for your Spree store. It allows you to manage products, orders, customers, and more.</p>
- </Card>
- <Card title="Storefront" icon="store">
- <p>The Storefront is the public-facing part of your Spree store where customers can browse products, add them to their cart, and complete purchases.</p>
- </Card>
- <Card title="Emails" icon="envelope">
- <p>Spree includes built-in support for sending transactional emails to customers, such as order confirmations and shipping notifications.</p>
- </Card>
- <Card title="Storefront API" icon="cart-shopping" href="/api-reference/storefront">
- <p>The Storefront API allows developers to interact with the Spree store programmatically, enabling custom front-end experiences and integrations.</p>
- </Card>
- <Card title="Platform API" icon="server" href="/api-reference/platform">
- <p>The Platform API provides a comprehensive set of endpoints for managing all aspects of the Spree store, including products, orders, and customers.</p>
- </Card>
- <Card title="Webhooks" icon="webhook">
- <p>Webhooks allow your Spree store to send real-time notifications to external systems when certain events occur, such as order creation or payment completion.</p>
- </Card>
-</CardGroup>
-
-### Code Conventions
-
-Spree is built on top of [Ruby on Rails framework](https://rubyonrails.org) and follows Model-View-Controller (MVC) architecture. As an example let's look at the Product model.
-
-* the model itself is located in [app/models/spree/product.rb](https://github.com/spree/spree/blob/main/core/app/models/spree/product.rb) and is named `Spree::Product`
-* the controller is located in [app/controllers/spree/products_controller.rb](https://github.com/spree/spree/blob/main/storefront/app/controllers/spree/products_controller.rb) and is named `Spree::ProductsController`
-* views for that controller are located in [app/views/spree/products](https://github.com/spree/spree/tree/main/storefront/app/views/spree/products) directory
+## Overview
+
+Spree is built around a set of interconnected models that represent the core concepts of e-commerce: products, orders, payments, and shipments. Understanding how these pieces fit together is essential for customizing and extending Spree.
+
+## Core Commerce Flow
+
+The following diagram shows how the main models interact during a typical customer purchase:
+
+```mermaid
+flowchart TB
+ subgraph Catalog["Catalog"]
+ Product --> Variant
+ Variant --> Price
+ Variant --> StockItem
+ StockItem --> StockLocation
+ end
+
+ subgraph Shopping["Shopping"]
+ User --> Order
+ Order --> LineItem
+ LineItem --> Variant
+ end
+
+ subgraph Checkout["Checkout"]
+ Order --> Address
+ Order --> Shipment
+ Order --> Payment
+ Shipment --> ShippingMethod
+ Payment --> PaymentMethod
+ end
+
+ subgraph Fulfillment["Fulfillment"]
+ Shipment --> InventoryUnit
+ InventoryUnit --> Variant
+ StockLocation --> Shipment
+ end
+
+ subgraph Pricing["Pricing & Adjustments"]
+ Order --> Adjustment
+ LineItem --> Adjustment
+ Shipment --> Adjustment
+ TaxRate --> Adjustment
+ Promotion --> Adjustment
+ end
+```
+
+**How it works:**
+
+1. **Catalog** - [Products](/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
+
+3. **Checkout** - The Order collects [Addresses](/developer/core-concepts/addresses), calculates [Shipping](/developer/core-concepts/shipments) options, and processes [Payments](/developer/core-concepts/payments)
+
+4. **Fulfillment** - [Shipments](/developer/core-concepts/shipments) are created from Stock Locations, tracking individual [Inventory Units](/developer/core-concepts/inventory#inventory-units)
+
+5. **Pricing & Adjustments** - [Taxes](/developer/core-concepts/taxes) and [Promotions](/developer/core-concepts/promotions) create [Adjustments](/developer/core-concepts/adjustments) that modify order totals
+
+## Core Model Relationships
+
+This diagram shows the key database relationships between Spree's main models:
+
+```mermaid
+erDiagram
+ Store ||--o{ Order : "has many"
+ Store ||--o{ Product : "has many"
+
+ Product ||--o{ Variant : "has many"
+ Product }o--|| TaxCategory : "belongs to"
+ Product }o--|| ShippingCategory : "belongs to"
+ Product }o--o{ Taxon : "categorized by"
+
+ Variant ||--o{ Price : "has many"
+ Variant ||--o{ StockItem : "has many"
+ Variant ||--o{ LineItem : "has many"
+
+ Order ||--o{ LineItem : "has many"
+ Order ||--o{ Shipment : "has many"
+ Order ||--o{ Payment : "has many"
+ Order ||--o{ Adjustment : "has many"
+ Order }o--|| User : "belongs to"
+ Order }o--|| Address : "ship address"
+ Order }o--|| Address : "bill address"
+
+ Shipment ||--o{ InventoryUnit : "has many"
+ Shipment }o--|| StockLocation : "ships from"
+ Shipment }o--|| ShippingMethod : "via"
+
+ Payment }o--|| PaymentMethod : "via"
+
+ StockLocation ||--o{ StockItem : "has many"
+
+ TaxRate }o--|| TaxCategory : "belongs to"
+ TaxRate }o--|| Zone : "applies to"
+ TaxRate ||--o{ Adjustment : "creates"
+
+ Promotion ||--o{ Adjustment : "creates"
+```
+
+## Multi-Store Architecture
+
+Spree supports multiple [Stores](/developer/core-concepts/stores) from a single installation. Each Store can have:
+
+- Its own domain and branding
+- Different currencies and locales
+- Separate product catalogs
+- Independent payment and shipping methods
+- Isolated orders and customers
+
+This makes Spree suitable for multi-brand retailers, international expansion, or B2B/B2C hybrid setups.
+
+## Extension Points
+
+Spree is designed to be customized without modifying core code. The main extension mechanisms are:
+
+| Mechanism | Use Case | Documentation |
+|-----------|----------|---------------|
+| **Events & Subscribers** | React to order completion, payment, shipment events | [Events Guide](/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 model/controller behavior (use sparingly) | [Decorators Guide](/developer/customization/decorators) |
<Info>
-All Spree code is prefixed with `Spree` namespace. Thanks to this convention, it's easy to identify Spree code in a Rails application and we will not have any conflicts with your application code or other libraries.
-</Info>
\ No newline at end of file
+For most customizations, prefer **Events** and **Dependencies** over Decorators. They're easier to maintain and won't break during upgrades.
+</Info>
+
+## Code Conventions
+
+Spree is built on [Ruby on Rails](https://rubyonrails.org) and follows Model-View-Controller (MVC) architecture. All Spree code is namespaced under `Spree::` to avoid conflicts with your application code.
+
+**Example: Product**
+
+| Component | Location | Class Name |
+|-----------|----------|------------|
+| Model | `core/app/models/spree/product.rb` | `Spree::Product` |
+| Admin Controller | `admin/app/controllers/spree/admin/products_controller.rb` | `Spree::Admin::ProductsController` |
+| API Serializer | `api/app/serializers/spree/v2/storefront/product_serializer.rb` | `Spree::V2::Storefront::ProductSerializer` |
+
+## Packages
+
+Spree is distributed as a set of Ruby gems (packages). Most users run Spree in **headless mode** with a custom frontend built using the [Storefront API](/api-reference/storefront) or [Platform API](/api-reference/platform).
+
+**Core packages** (required):
+
+| Package | Purpose |
+|---------|---------|
+| `spree_core` | Models, services, and business logic |
+| `spree_api` | [Storefront API](/api-reference/storefront), [Platform API](/api-reference/platform), and [Webhooks](/developer/core-concepts/webhooks) |
+
+**Optional packages:**
+
+| Package | Purpose |
+|---------|---------|
+| `spree_admin` | Admin dashboard for managing your store |
+| `spree_cli` | CLI tool to interact with your Spree installation |
+| `spree_storefront` | Pre-built Rails storefront (not needed for headless setups) |
+| `spree_emails` | Transactional email templates (order confirmation, shipping, etc.) |
+| `spree_page_builder` | Visual page builder for the Rails storefront |
+| `spree_sample` | Sample data (products, categories, etc.) for development and testing |
+| `spree_dev_tools` | Development and testing utilities for Spree applications and extensions |
+
+<Info>
+For headless commerce, you only need `spree_core` and `spree_api`. Build your customer-facing frontend with any technology (Next.js, Nuxt, mobile apps) using the Storefront API.
+</Info>
+
+## Related Documentation
+
+- [Products](/developer/core-concepts/products) - Product catalog and variants
+- [Orders](/developer/core-concepts/orders) - Order lifecycle and state machine
+- [Payments](/developer/core-concepts/payments) - Payment processing
+- [Shipments](/developer/core-concepts/shipments) - Shipping and fulfillment
+- [Customization Quickstart](/developer/customization/quickstart) - How to extend Spree
\ No newline at end of file
diff --git a/docs/developer/core-concepts/calculators.mdx b/docs/developer/core-concepts/calculators.mdx
index 5fd7832a32..19d9359d4a 100644
--- a/docs/developer/core-concepts/calculators.mdx
+++ b/docs/developer/core-concepts/calculators.mdx
@@ -4,6 +4,51 @@ title: Calculators
## Overview
+### Calculator Model Diagram
+
+```mermaid
+erDiagram
+ Calculator {
+ string type
+ string calculable_type
+ text preferences
+ }
+
+ TaxRate {
+ string name
+ decimal amount
+ boolean included_in_price
+ }
+
+ ShippingMethod {
+ string name
+ string display_on
+ }
+
+ PromotionAction {
+ string type
+ }
+
+ Adjustment {
+ decimal amount
+ string label
+ }
+
+ TaxRate ||--|| Calculator : "has one"
+ ShippingMethod ||--|| Calculator : "has one"
+ PromotionAction ||--|| Calculator : "has one"
+ TaxRate ||--o{ Adjustment : "creates"
+ ShippingMethod ||--o{ ShippingRate : "calculates"
+ PromotionAction ||--o{ Adjustment : "creates"
+```
+
+**Key relationships:**
+- **Calculator** computes amounts for various features
+- Used by **[Tax Rates](/developer/core-concepts/taxes)** to calculate tax amounts
+- Used by **[Shipping Methods](/developer/core-concepts/shipments)** to calculate shipping costs
+- Used by **[Promotion Actions](/developer/core-concepts/promotions)** to calculate discounts
+- Calculators store preferences (rates, percentages, etc.) for their calculations
+
Spree makes extensive use of the `Spree::Calculator` model and there are several subclasses provided to deal with various types of calculations flat rate, percentage discount, sales tax, VAT, etc. All calculators extend the `Spree::Calculator` class and must provide the following methods:
```ruby
@@ -177,9 +222,11 @@ The second thing is to register this calculator as a tax, shipping, or promotion
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.calculators.tax_rates << CustomCalculator
- Spree.calculators.shipping_methods << CustomCalculator
- Spree.calculators.promotion_actions_create_adjustments << CustomCalculator
+ 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">
@@ -196,7 +243,9 @@ For example if your calculator is placed in `app/models/spree/calculator/shippin
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.calculators.shipping_methods << Spree::Calculator::Shipping::MyOwnCalculator
+ Rails.application.config.after_initialize do
+ Spree.calculators.shipping_methods << Spree::Calculator::Shipping::MyOwnCalculator
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
@@ -233,7 +282,9 @@ To have calculators available for this class, you will need to register them:
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.calculators.plans << CustomCalculator
+ Rails.application.config.after_initialize do
+ Spree.calculators.plans << CustomCalculator
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
diff --git a/docs/developer/core-concepts/events.mdx b/docs/developer/core-concepts/events.mdx
index 8de3755608..7b2df157c1 100644
--- a/docs/developer/core-concepts/events.mdx
+++ b/docs/developer/core-concepts/events.mdx
@@ -668,3 +668,6 @@ See `Spree::Events::Adapters::ActiveSupportNotifications` for a complete referen
## Related Documentation
- [Webhooks](/developer/core-concepts/webhooks) - HTTP callbacks for external integrations
+- [Customization Quickstart](/developer/customization/quickstart) - Overview of all customization options
+- [Decorators](/developer/customization/decorators) - When to use decorators vs events
+- [Checkout Flow](/developer/customization/checkout) - Using events in checkout customization
diff --git a/docs/developer/core-concepts/i18n.mdx b/docs/developer/core-concepts/i18n.mdx
index 2688356cbb..d8afc0382d 100644
--- a/docs/developer/core-concepts/i18n.mdx
+++ b/docs/developer/core-concepts/i18n.mdx
@@ -75,14 +75,14 @@ Spree::Product.joins(:taxons)
```
<Info>
- If you are using Spree version 4.5 or order and are currently unable to upgrade, you can install [Spree Globalize extension](https://github.com/spree-contrib/spree_globalize) to enable translations. This extension uses [Globalize](https://github.com/globalize/globalize) library under the hood. We do not recommend this approach and we will not be providing support for it. We recommend upgrading to the Spree 4.6 or newer.
+ If you are using Spree version 4.5 or older and are currently unable to upgrade, you can install [Spree Globalize extension](https://github.com/spree-contrib/spree_globalize) to enable translations. This extension uses [Globalize](https://github.com/globalize/globalize) library under the hood. We do not recommend this approach and we will not be providing support for it. We recommend upgrading to Spree 4.6 or newer.
</Info>
## The `spree_i18n` project
Spree now stores all of the translation information in a separate GitHub project known as [Spree I18n](https://github.com/spree/spree_i18n). This is a stand alone project with a large number of volunteer committers who maintain the locale files. This is basically the same approach followed by the Rails project which keeps their localizations in [rails-i18n](https://github.com/svenfuchs/rails-i18n).
-The project is actually a Spree extension. This extension contains translations files. To translate models (provide translations for Products, Taxons, etc) you will need to install also [Spree Globalize](https://github.com/spree-contrib/spree_globalize).
+The project is actually a Spree extension. This extension contains translation files for the Spree UI in various languages.
To install the Spree I18n extension, run the following command:
@@ -138,3 +138,9 @@ en:
[Spree extensions](/developer/customization/extensions) can contain their own `config/locales` directory where developers can include YAML files for each language they wish to support.
We strongly urge all extension developers to ensure all customer facing text is rendered via the `Spree.t()` helper method even if they only include a single default language locale file (as other users can simply include the required YAML file and translations in their site extension).
+
+## Related Documentation
+
+- [Stores](/developer/core-concepts/stores) - Multi-store and multi-language configuration
+- [Products](/developer/core-concepts/products) - Product translations
+- [Extensions](/developer/customization/extensions) - Creating extensions with translations
diff --git a/docs/developer/core-concepts/inventory.mdx b/docs/developer/core-concepts/inventory.mdx
index e20dee696a..c2dafc14a7 100644
--- a/docs/developer/core-concepts/inventory.mdx
+++ b/docs/developer/core-concepts/inventory.mdx
@@ -4,12 +4,71 @@ title: Inventory
## Overview
-In Spree each Variant has a `StockItem`. This is the place where the inventory for that variant is stored. Variant can have multiple `StockItems` if they are available in multiple `StockLocations`.
+In Spree each [Variant](/developer/core-concepts/products#variants) has a `StockItem`. This is the place where the inventory for that variant is stored. A Variant can have multiple `StockItems` if it is available in multiple `StockLocations`.
Back-ordered, sold, or shipped products are stored as individual `InventoryUnit` objects so they can have relevant information attached to them.
New products created in the system can be given a starting "on hand" inventory level. You can subsequently set new inventory levels and the correct things will happen, e.g. adding new on-hand inventory to an out-of-stock product that has some backorders will first fill the backorders then update the product with the remaining inventory count.
+### Inventory Model Diagram
+
+```mermaid
+erDiagram
+ StockLocation {
+ string name
+ string admin_name
+ boolean active
+ boolean default
+ boolean backorderable_default
+ boolean propagate_all_variants
+ }
+
+ StockItem {
+ integer count_on_hand
+ boolean backorderable
+ integer stock_location_id
+ integer variant_id
+ }
+
+ StockMovement {
+ integer quantity
+ string originator_type
+ integer originator_id
+ integer stock_item_id
+ }
+
+ StockTransfer {
+ string number
+ string reference
+ integer source_location_id
+ integer destination_location_id
+ }
+
+ InventoryUnit {
+ string state
+ integer variant_id
+ integer order_id
+ integer shipment_id
+ }
+
+ 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"
+ StockTransfer ||--o{ StockMovement : "has many"
+ Order ||--o{ InventoryUnit : "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/shipments)
+
## Inventory Management
### Stock Locations
@@ -136,3 +195,9 @@ variant.update(track_inventory: false)
```
This can also be done via the Admin Panel or Platform API.
+
+## Related Documentation
+
+- [Products](/developer/core-concepts/products) - Product and variant management
+- [Shipments](/developer/core-concepts/shipments) - How inventory relates to shipments
+- [Orders](/developer/core-concepts/orders) - How inventory is allocated to orders
diff --git a/docs/developer/core-concepts/orders.mdx b/docs/developer/core-concepts/orders.mdx
index 9d0280a2e2..5ed899efa0 100644
--- a/docs/developer/core-concepts/orders.mdx
+++ b/docs/developer/core-concepts/orders.mdx
@@ -6,6 +6,79 @@ title: Orders
The `Order` model is one of the key models in Spree. It provides a central place around which to collect information about a customer order - including line items, adjustments, payments, addresses, return authorizations, and shipments.
+### Order Model Diagram
+
+```mermaid
+erDiagram
+ Order {
+ string number
+ string state
+ string email
+ decimal item_total
+ decimal adjustment_total
+ decimal total
+ decimal payment_total
+ decimal shipment_total
+ string payment_state
+ string shipment_state
+ datetime completed_at
+ string currency
+ }
+
+ LineItem {
+ integer quantity
+ decimal price
+ decimal adjustment_total
+ }
+
+ Shipment {
+ string number
+ string state
+ string tracking
+ datetime shipped_at
+ }
+
+ Payment {
+ string number
+ decimal amount
+ string state
+ string response_code
+ }
+
+ Adjustment {
+ decimal amount
+ string label
+ boolean eligible
+ string state
+ boolean included
+ }
+
+ Order ||--o{ LineItem : "has many"
+ Order ||--o{ Shipment : "has many"
+ Order ||--o{ Payment : "has many"
+ Order ||--o{ Adjustment : "has many"
+ Order ||--o{ ReturnAuthorization : "has many"
+ Order ||--o{ OrderPromotion : "has many"
+ Order }o--|| Address : "ship_address"
+ Order }o--|| Address : "bill_address"
+ Order }o--|| User : "belongs to"
+ Order }o--|| Store : "belongs to"
+ LineItem }o--|| Variant : "belongs to"
+ LineItem ||--o{ Adjustment : "has many"
+ Shipment ||--o{ InventoryUnit : "has many"
+ Shipment ||--o{ Adjustment : "has many"
+ Shipment }o--|| StockLocation : "ships from"
+ Payment }o--|| PaymentMethod : "belongs to"
+```
+
+**Key relationships:**
+- **Order** is the central model connecting customers to their purchases
+- **Line Items** link orders to [Variants](/developer/core-concepts/products#variants) (what was purchased)
+- **[Shipments](/developer/core-concepts/shipments)** handle fulfillment from [Stock Locations](/developer/core-concepts/inventory#stock-locations)
+- **[Payments](/developer/core-concepts/payments)** track payment attempts and their states
+- **[Adjustments](/developer/core-concepts/adjustments)** apply taxes, promotions, and shipping costs
+- **[Addresses](/developer/core-concepts/addresses)** store billing and shipping information
+
### Order Attributes
| Attribute | Description |
@@ -134,7 +207,7 @@ For more on this please go to [Payment States page](payments).
## Line Items
-Line items are used to keep track of items within the context of an order. These records provide a link between orders, and [Variants](products#variants).
+Line items are used to keep track of items within the context of an order. These records provide a link between orders and [Variants](/developer/core-concepts/products#variants).
<Warning>
When a variant is added to an order, the price of that item is tracked along with the line item to preserve that data. If the variant's price were to change, then the line item would still have a record of the price at the time of ordering.
@@ -150,7 +223,7 @@ For more information about addresses, please read the [Addresses](/developer/cor
## Adjustments
-Adjustments are used to affect an order's final cost, either by decreasing it [Promotions](promotions) or by increasing it [Shipping](shipments), [Taxes](taxation).
+Adjustments are used to affect an order's final cost, either by decreasing it ([Promotions](/developer/core-concepts/promotions)) or by increasing it ([Shipping](/developer/core-concepts/shipments), [Taxes](/developer/core-concepts/taxes)).
For more information about adjustments, please see the [Adjustments](adjustments) guide.
@@ -171,3 +244,11 @@ If you change any aspect of an `Order` object within code and you wish to update
For example, if you create or modify an existing payment for the order which would change the order's `payment_state` to a different value, calling `update_with_updater!` will cause the `payment_state` to be recalculated for that order.
Another example is if a `LineItem` within the order had its price changed. Calling `update_with_updater!` will cause the totals for the order to be updated, the adjustments for the order to be recalculated, and then a final total to be established.
+
+## Related Documentation
+
+- [Payments](/developer/core-concepts/payments) - Payment processing for orders
+- [Shipments](/developer/core-concepts/shipments) - Order fulfillment and shipping
+- [Promotions](/developer/core-concepts/promotions) - Discounts and promotions
+- [Checkout Customization](/developer/customization/checkout) - Customizing the checkout flow
+- [Events](/developer/core-concepts/events) - Subscribe to order events
diff --git a/docs/developer/core-concepts/payments.mdx b/docs/developer/core-concepts/payments.mdx
index 3ca00b16a2..f27b2a3ae2 100644
--- a/docs/developer/core-concepts/payments.mdx
+++ b/docs/developer/core-concepts/payments.mdx
@@ -12,6 +12,75 @@ The `Payment` model in Spree tracks payments against [Orders](orders). Payments
When a payment is created, it is given a unique, 8-character identifier. This is used when sending the payment details to the payment processor. Without this identifier, some payment gateways mistakenly reported duplicate payments.
+### Payment Model Diagram
+
+```mermaid
+erDiagram
+ Payment {
+ string number
+ decimal amount
+ string state
+ string response_code
+ string avs_response
+ string source_type
+ integer source_id
+ }
+
+ PaymentMethod {
+ string name
+ string type
+ string description
+ boolean active
+ string display_on
+ integer position
+ }
+
+ CreditCard {
+ string last_digits
+ string cc_type
+ integer month
+ integer year
+ string name
+ string gateway_customer_profile_id
+ string gateway_payment_profile_id
+ }
+
+ StoreCredit {
+ decimal amount
+ decimal amount_used
+ decimal amount_authorized
+ string currency
+ }
+
+ Refund {
+ decimal amount
+ string reason
+ }
+
+ LogEntry {
+ text details
+ }
+
+ Order ||--o{ Payment : "has many"
+ Payment }o--|| PaymentMethod : "belongs to"
+ Payment }o--o| CreditCard : "source"
+ Payment }o--o| StoreCredit : "source"
+ Payment ||--o{ LogEntry : "has many"
+ Payment ||--o{ Refund : "has many"
+ PaymentMethod }o--|| Store : "belongs to"
+ CreditCard }o--|| User : "belongs to"
+ StoreCredit }o--|| User : "belongs to"
+ Refund }o--|| Payment : "belongs to"
+ Refund }o--|| Reimbursement : "belongs to"
+```
+
+**Key relationships:**
+- **Payment** tracks each payment attempt against an [Order](/developer/core-concepts/orders)
+- **Payment Method** defines how payments are processed (Stripe, PayPal, Check, etc.)
+- **Source** is polymorphic - can be a Credit Card, Store Credit, or other payment sources
+- **Log Entries** record gateway responses for debugging
+- **Refunds** track money returned to customers
+
## Payment States
A payment can go through many different states:
@@ -227,7 +296,9 @@ Next, add your custom gateway to the list of available payment methods in `confi
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.payment_methods << FancyPaymentMethod
+ Rails.application.config.after_initialize do
+ Spree.payment_methods << FancyPaymentMethod
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
@@ -263,4 +334,10 @@ class FancyPaymentMethod < Spree::PaymentMethod
end
```
-This code will make the payment method available only for orders with a total greater than 100 and currency USD.
\ No newline at end of file
+This code will make the payment method available only for orders with a total greater than 100 and currency USD.
+
+## Related Documentation
+
+- [Orders](/developer/core-concepts/orders) - Order management and state machine
+- [Checkout Customization](/developer/customization/checkout) - Customizing the checkout flow
+- [Events](/developer/core-concepts/events) - Subscribe to payment events
\ No newline at end of file
diff --git a/docs/developer/core-concepts/products.mdx b/docs/developer/core-concepts/products.mdx
index a969605272..7bcf8ae3ba 100644
--- a/docs/developer/core-concepts/products.mdx
+++ b/docs/developer/core-concepts/products.mdx
@@ -4,12 +4,94 @@ title: Products
## Overview
-`Product` records track unique products within your store. These differ from [Variants](#variants), which track the unique variations of a product. For instance, a product that's a T-shirt would have variants denoting its different colors and sizes. Together, Products and Variants describe what is for sale.
+`Product` records track unique products within your store. These differ from [Variants](#variants), which track the unique variations of a product. For instance, a product that's a T-shirt would have variants denoting its different colors and sizes. Together, Products and Variants describe what is for sale.
<Info>
Note that as of version 4.6, certain product fields are translatable (read more about this in [Internationalization](/developer/core-concepts/i18n#resource-translations)).
</Info>
+### Product Model Diagram
+
+```mermaid
+erDiagram
+ Product {
+ string name
+ string slug
+ string status
+ text description
+ datetime available_on
+ datetime discontinue_on
+ string meta_title
+ string meta_description
+ }
+
+ Variant {
+ string sku
+ string barcode
+ decimal weight
+ decimal height
+ decimal width
+ decimal depth
+ boolean is_master
+ boolean track_inventory
+ decimal cost_price
+ }
+
+ Price {
+ decimal amount
+ decimal compare_at_amount
+ string currency
+ }
+
+ OptionType {
+ string name
+ string presentation
+ integer position
+ }
+
+ OptionValue {
+ string name
+ string presentation
+ integer position
+ }
+
+ Taxon {
+ string name
+ string permalink
+ text description
+ integer position
+ }
+
+ Taxonomy {
+ string name
+ integer position
+ }
+
+ Product ||--o{ Variant : "has many"
+ Product }o--o{ OptionType : "has many"
+ Product ||--o{ Classification : "has many"
+ Product ||--o{ ProductProperty : "has many"
+ Product }o--|| ShippingCategory : "belongs to"
+ Product }o--|| TaxCategory : "belongs to"
+ Variant ||--o{ Price : "has many"
+ Variant ||--o{ StockItem : "has many"
+ Variant ||--o{ Image : "has many"
+ Variant }o--o{ OptionValue : "has many"
+ OptionType ||--o{ OptionValue : "has many"
+ Taxon ||--o{ Classification : "has many"
+ Taxonomy ||--o{ Taxon : "has many"
+ Property ||--o{ ProductProperty : "has many"
+```
+
+**Key relationships:**
+- **Product** has one master Variant and many regular Variants
+- **Variants** represent purchasable items with SKU, price, and [inventory](/developer/core-concepts/inventory)
+- **Option Types** (e.g., Size, Color) define variant options
+- **Option Values** (e.g., Small, Red) are assigned to variants
+- **Taxons** (via Classifications) organize products into categories
+- **Properties** store additional product attributes (e.g., Material, Brand)
+- **[Shipping Category](/developer/core-concepts/shipments)** and **[Tax Category](/developer/core-concepts/taxes)** determine shipping and tax rules
+
Products have the following attributes:
| Attribute | Description | Translatable |
diff --git a/docs/developer/core-concepts/promotions.mdx b/docs/developer/core-concepts/promotions.mdx
index 96fe774975..7b07fabdff 100644
--- a/docs/developer/core-concepts/promotions.mdx
+++ b/docs/developer/core-concepts/promotions.mdx
@@ -1,111 +1,447 @@
---
title: Promotions
+description: Learn about Spree's flexible promotion system for discounts, free shipping, and gifts.
---
## Overview
-Promotions within Spree are used to provide discounts to orders, offer free shipping or to add potential additional items at no extra cost (eg. samples).
+Promotions within Spree are used to provide discounts to orders, offer free shipping, or add items at no extra cost (e.g., free gifts). The promotion system is highly flexible, allowing you to create complex promotional campaigns based on various conditions.
-Promotions are one of the most complex areas within Spree, as there are a large number of moving parts to consider. Although this guide will explain Promotions from a developer's perspective, if you are new to this area you can learn a lot from the Admin &gt; Promotions tab where you can set up new Promotions, edit rules & actions, etc.
+### Promotion Model Diagram
-Promotions can be activated in three different ways:
+```mermaid
+erDiagram
+ Promotion {
+ string name
+ string description
+ string kind
+ string code
+ string path
+ datetime starts_at
+ datetime expires_at
+ integer usage_limit
+ string match_policy
+ boolean advertise
+ }
-* When a user adds a product to their cart (automatic promotions, eg. free shipping with a threshold)
-* When a user enters a coupon code during the checkout process
+ PromotionRule {
+ string type
+ text preferences
+ }
-Promotions for these individual ways are activated through their corresponding [PromotionHandler class](https://github.com/spree/spree/tree/main/core/app/models/spree/promotion_handler), once they've been checked for eligibility.
+ PromotionAction {
+ string type
+ integer position
+ }
-Promotions relate to two other main components: `actions` and `rules`. When a promotion is activated, the actions for the promotion are performed, passing in the payload from the `fire_event` call that triggered the activator becoming active. Rules are used to determine if a promotion meets certain criteria in order to be applicable.
+ CouponCode {
+ string code
+ string state
+ }
-Here is a table showcasing the attributes of the `Spree::Promotion` model along with a description for each attribute and example values:
+ OrderPromotion {
+ integer order_id
+ integer promotion_id
+ }
-| Attribute | Description | Example Value |
-|--------------------------|-------------------------------------------------------|------------------------|
-| `name` | The name of the promotion | Summer Sale |
-| `description` | A brief description of the promotion | Discounts for summer |
-| `expires_at` | The expiration date and time of the promotion | 2025-09-01 23:59:59 |
-| `starts_at` | The start date and time of the promotion | 2025-06-01 00:00:00 |
-| `code` | A code that users can enter to apply the promotion | `SUMMER2023` |
-| `usage_limit` | The total number of times the promotion can be used | 500 |
-| `match_policy` | The policy for how promotion rules are matched | `all` |
-| `code_prefix` | A prefix for generated coupon codes | `SUMMER` |
-| `number_of_codes` | The number of unique codes to be generated for the promotion| 1000 |
-| `kind` | The type of promotion (coupon_code or automatic) | `coupon_code` |
-| `multi_codes` | Indicates if the promotion uses multiple coupon codes | `false` |
+ Adjustment {
+ decimal amount
+ string label
+ boolean eligible
+ string state
+ }
-## Actions
+ Promotion ||--o{ PromotionRule : "has many"
+ Promotion ||--o{ PromotionAction : "has many"
+ Promotion ||--o{ CouponCode : "has many"
+ Promotion ||--o{ OrderPromotion : "has many"
+ Promotion }o--o{ Store : "available in"
+ PromotionRule }o--o{ Product : "applies to"
+ PromotionRule }o--o{ Taxon : "applies to"
+ PromotionRule }o--o{ User : "applies to"
+ PromotionAction ||--o{ Adjustment : "creates"
+ PromotionAction ||--|| Calculator : "has one"
+ Order ||--o{ OrderPromotion : "has many"
+ CouponCode }o--o| Order : "used by"
+```
+
+**Key relationships:**
+- **Promotion** defines the campaign with rules and actions
+- **Promotion Rules** determine eligibility conditions (FirstOrder, ItemTotal, Taxon, etc.)
+- **Promotion Actions** define what happens when applied (discount, free shipping, free items)
+- **Coupon Codes** track usage for code-based promotions
+- **[Adjustments](/developer/core-concepts/adjustments)** are created on orders/line items to apply discounts
+
+Promotions can be activated in two ways:
+
+- **Automatic promotions** - Applied automatically when eligibility rules are met (e.g., free shipping on orders over $50)
+- **Coupon code promotions** - Applied when a customer enters a valid code during checkout
+
+Promotions consist of two main components:
+
+- **Rules** - Conditions that must be met for the promotion to apply
+- **Actions** - What happens when the promotion is applied (discount, free shipping, etc.)
+
+## Promotion Attributes
-There are four actions that come with Spree:
-
-<AccordionGroup>
- <Accordion title="Creating an Adjustment">
- <p>When a <code>CreateAdjustment</code> action is undertaken, an adjustment is automatically applied to the order, unless the promotion has already applied an adjustment to the order.</p>
- <p>Once the adjustment has been applied to the order, its eligibility is re-checked every time the order is saved, by way of the <code>Promotion#eligible?</code> method, which uses <code>Promotion#eligible_rules</code> to determine if the promotion is still eligible based on its rules. For how this process works, please see the <a href="#rules">rules section</a> below.</p>
- <p>An adjustment to order from a promotion depends on the calculators. For more information about calculators, please see the <a href="calculators">Calculators guide</a>.</p>
- </Accordion>
- <Accordion title="Creating an Item Adjustment">
- <p>When a <code>CreateItemAdjustments</code> action is undertaken, an adjustment is automatically applied to each item within the order unless the action has already been performed on that line item.</p>
- <p>The eligibility of the item for this promotion is re-checked whenever the item is updated. Its eligibility is based on the rules of the promotion.</p>
- <p>An adjustment to order from a promotion depends on the calculators. For more information about calculators, please see the <a href="calculators">Calculators guide</a>.</p>
- </Accordion>
- <Accordion title="Free Shipping">
- <p>When a <code>FreeShipping</code> action is undertaken, all shipments within the order have their prices negated. Just like with prior actions, the eligibility of this promotion is checked again whenever a shipment changes.</p>
- </Accordion>
- <Accordion title="Create Line Items">
- <p>When a <code>CreateLineItem</code> action is undertaken, a series of line items are automatically added to the order, which may alter the order's price. The promotion with an action to add a line item can also have another action to add an adjustment to the order to nullify the cost of adding the product to the order.</p>
- </Accordion>
-</AccordionGroup>
+| Attribute | Description | Example |
+|-----------|-------------|---------|
+| `name` | The name of the promotion | Summer Sale |
+| `description` | Brief description (max 255 chars) | 20% off all summer items |
+| `kind` | Type: `coupon_code` or `automatic` | `automatic` |
+| `starts_at` | When the promotion becomes active | 2025-06-01 00:00:00 |
+| `expires_at` | When the promotion expires | 2025-09-01 23:59:59 |
+| `usage_limit` | Max times the promotion can be used | 500 |
+| `match_policy` | How rules are evaluated: `all` or `any` | `all` |
+| `advertise` | Whether to display on storefront | `true` |
+| `path` | SEO-friendly URL path | `summer-sale` |
+
+### Multi-Code Promotions
+
+For promotions that need unique codes per customer (e.g., influencer campaigns), Spree supports bulk code generation:
+
+| Attribute | Description | Example |
+|-----------|-------------|---------|
+| `multi_codes` | Enable bulk code generation | `true` |
+| `number_of_codes` | How many codes to generate | 1000 |
+| `code_prefix` | Prefix for generated codes | `SUMMER` |
+
+Generated codes follow the pattern `{prefix}{random}`, e.g., `SUMMER22A0F62A230BD919`.
## Rules
-Here's a list of all the rules that come with Spree:
-
-<AccordionGroup>
- <Accordion title="FirstOrder">
- The user's order is their first.
- </Accordion>
- <Accordion title="ItemTotal">
- The order's total is greater than (or equal to) a given value.
- </Accordion>
- <Accordion title="Product">
- An order contains a specific product.
- </Accordion>
- <Accordion title="User">
- The order is by a specific user. Only customers who have an account can use this rule.
- </Accordion>
- <Accordion title="UserLoggedIn">
- The user is logged in.
- </Accordion>
- <Accordion title="One Use Per User">
- Can be used only once per customer. Only customers who have an account can use this rule.
- </Accordion>
- <Accordion title="Taxon(s)">
- Order includes product(s) associated with Taxons that are selected for this rule.
- </Accordion>
- <Accordion title="Country">
- Checks if Order's ship address country matches the selected country, eg. US-only Orders
- </Accordion>
-</AccordionGroup>
-
-Rules are used by Spree to determine if a promotion is applicable to an order and can be matched in one of two ways: all of the rules must match, or one rule must match. This is determined by the `match_policy` attribute on the `Promotion` object. As you will see in the Admin, you can set the match_policy to be "any" or "all" of the rules associated with the Promotion. When set to "any" the Promotion will be considered eligible if any one of the rules applies, when set to "all" it will be eligible only if all the rules apply.
+Rules determine when a promotion is eligible. You can combine multiple rules and configure whether **all** rules must match or **any** rule is sufficient (via `match_policy`).
+
+### FirstOrder
+
+Applies only to a customer's first order. Checks both user account and email address to prevent abuse.
+
+**Use case:** Welcome discount for new customers.
+
+### ItemTotal
+
+Requires the order subtotal to meet minimum and/or maximum thresholds.
+
+**Configuration:**
+- `preferred_amount_min` - Minimum order amount (default: 100.00)
+- `preferred_operator_min` - Comparison operator: `gt` (greater than) or `gte` (greater than or equal)
+- `preferred_amount_max` - Maximum order amount (optional)
+- `preferred_operator_max` - Comparison operator: `lt` (less than) or `lte` (less than or equal)
+
+**Use case:** "Free shipping on orders over $50", "10% off orders between $100-$500".
+
+### Product
+
+Requires specific products to be in the order.
+
+**Configuration:**
+- `preferred_match_policy`:
+ - `any` - At least one of the specified products
+ - `all` - All specified products must be present
+ - `none` - None of the specified products (exclusion)
+
+**Use case:** "Buy Product A and get 20% off", "Discount excludes sale items".
+
+### Taxon
+
+Requires products from specific categories (taxons) to be in the order.
+
+**Configuration:**
+- `preferred_match_policy`: `any` or `all`
+
+The rule automatically includes products in child taxons when a parent taxon is selected.
+
+**Use case:** "20% off Electronics", "Buy from Shoes category get 10% off".
+
+### User
+
+Limits the promotion to specific customer accounts.
+
+**Use case:** Employee discounts, VIP customer promotions.
+
+### UserLoggedIn
+
+Requires the customer to be logged in with an account.
+
+**Use case:** Member-only discounts.
+
+### OneUsePerUser
+
+Ensures each customer can only use the promotion once.
+
+**Use case:** One-time welcome offers, limited redemption campaigns.
+
+### Country
+
+Limits the promotion to orders shipping to a specific country.
+
+**Configuration:**
+- `preferred_country_id` or `preferred_country_iso` (ISO 2-letter code)
+
+**Use case:** Regional promotions, country-specific campaigns.
+
+### Currency
+
+Limits the promotion to orders in a specific currency.
+
+**Configuration:**
+- `preferred_currency` - Currency code (e.g., "USD", "EUR")
+
+**Use case:** Currency-specific pricing strategies.
+
+### OptionValue
+
+Requires products with specific option values (e.g., size, color) to be in the order.
+
+**Configuration:**
+- `preferred_eligible_values` - Array of eligible variant IDs
+
+**Use case:** "10% off all red items", "Discount on size XL".
+
+### CustomerGroup
+
+Limits the promotion to customers belonging to specific customer groups.
+
+**Configuration:**
+- `preferred_customer_group_ids` - Array of customer group IDs
+
+Customer groups are managed in Admin > Customers > Customer Groups and allow you to segment customers for targeted promotions.
+
+**Use case:** VIP programs, loyalty tiers, wholesale pricing, B2B customer segments.
+
+## Actions
+
+Actions define what happens when a promotion is applied.
+
+### CreateAdjustment
+
+Creates a discount on the entire order total.
+
+**Default calculator:** `FlatPercentItemTotal` (percentage off order)
+
+**Available calculators:**
+- `FlatPercentItemTotal` - Percentage off the order total
+- `FlatRate` - Fixed amount off
+- `FlexiRate` - First item at one rate, additional items at another
+- `TieredFlatRate` - Different rates based on order total tiers
+- `TieredPercent` - Different percentages based on order total tiers
+
+**Use case:** "10% off your order", "$20 off orders over $100".
+
+### CreateItemAdjustments
+
+Creates discounts on individual line items. Only applies to items that match the promotion rules (e.g., items in a specific category).
+
+**Default calculator:** `PercentOnLineItem` (percentage off each item)
+
+The action respects rule actionability - if a Taxon rule specifies "Electronics", only electronics items receive the discount.
+
+**Use case:** "15% off shoes", "Buy 2+ shirts get 10% off each".
+
+### FreeShipping
+
+Makes all shipments free by creating negative adjustments equal to shipping costs.
+
+**Use case:** "Free shipping on orders over $75", "Free shipping with code FREESHIP".
+
+### CreateLineItems
+
+Automatically adds specified products to the cart when the promotion is eligible.
+
+**Configuration:**
+- Map of variant IDs to quantities to add
+
+The action checks stock availability before adding items. Items are not automatically removed if eligibility is lost - customers must remove them manually.
+
+**Use case:** "Free gift with purchase", "Buy 2 get 1 free", "Spend $100 get free sample".
## Coupon Codes
-Coupon codes are a way to track the usage of a promotion. They are associated with a promotion and can be used to apply the promotion to an order.
+Coupon codes track promotion usage and can be single-use or multi-use.
+
+### Single Code Promotions
+
+Set the `code` attribute directly on the promotion. The `usage_limit` controls how many times it can be redeemed.
+
+### Multi-Code Promotions
+
+For bulk-generated codes, each code is stored in the `spree_coupon_codes` table:
+
+| Attribute | Description | Example |
+|-----------|-------------|---------|
+| `code` | The unique code | `SUMMER22A0F62A230BD919` |
+| `promotion_id` | Associated promotion | 123 |
+| `order_id` | Order that used the code | 456 |
+| `state` | Usage state | `unused`, `used` |
+
+## Custom Promotion Rules
+
+You can create custom rules to implement business-specific eligibility logic.
+
+### Step 1: Create the Rule Class
+
+```bash
+mkdir -p app/models/spree/promotion/rules
+```
+
+```ruby app/models/spree/promotion/rules/minimum_quantity.rb
+module Spree
+ class Promotion
+ module Rules
+ class MinimumQuantity < Spree::PromotionRule
+ preference :quantity, :integer, default: 5
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def eligible?(order, options = {})
+ total_quantity = order.line_items.sum(&:quantity)
+
+ if total_quantity >= preferred_quantity
+ true
+ else
+ eligibility_errors.add(:base, "Order must contain at least #{preferred_quantity} items")
+ false
+ end
+ end
+ end
+ end
+ end
+end
+```
+
+The `eligible?` method should return `true` or `false`. Use `eligibility_errors` to provide feedback to customers about why the promotion didn't apply.
+
+### Step 2: Register the Rule
+
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.after_initialize do
+ Spree.promotions.rules << Spree::Promotion::Rules::MinimumQuantity
+ end
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.after_initialize do
+ Rails.application.config.spree.promotions.rules << Spree::Promotion::Rules::MinimumQuantity
+ end
+ ```
+ </Tab>
+</Tabs>
+
+### Step 3: Create the Admin Partial
+
+```bash
+touch app/views/spree/admin/promotions/rules/_minimum_quantity.html.erb
+```
+
+```erb app/views/spree/admin/promotions/rules/_minimum_quantity.html.erb
+<div class="row mb-3">
+ <%= f.spree_number_field :preferred_quantity, label: Spree.t(:minimum_quantity) %>
+</div>
+```
+
+### Step 4: Add Translations
+
+```yaml config/locales/en.yml
+en:
+ spree:
+ minimum_quantity: Minimum Quantity
+ promotion_rule_types:
+ minimum_quantity:
+ name: Minimum Quantity
+ description: Order must contain at least X items
+```
+
+### Step 5: Restart Your Application
+
+After restarting, the new rule will be available in the Admin > Promotions interface.
+
+## Custom Promotion Actions
+
+You can create custom actions to implement business-specific promotion behaviors.
+
+### Step 1: Create the Action Class
+
+```bash
+mkdir -p app/models/spree/promotion/actions
+```
+
+```ruby app/models/spree/promotion/actions/add_loyalty_points.rb
+module Spree
+ module Promotion
+ module Actions
+ class AddLoyaltyPoints < Spree::PromotionAction
+ preference :points, :integer, default: 100
+
+ def perform(options = {})
+ order = options[:order]
+ return false unless order.user.present?
+
+ # Add loyalty points to the user
+ order.user.add_loyalty_points(preferred_points, source: promotion)
+ true
+ end
+ end
+ end
+ end
+end
+```
+
+The `perform` method should return `true` if the action was successfully applied, `false` otherwise.
+
+### Step 2: Register the Action
+
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.after_initialize do
+ Spree.promotions.actions << Spree::Promotion::Actions::AddLoyaltyPoints
+ end
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.after_initialize do
+ Rails.application.config.spree.promotions.actions << Spree::Promotion::Actions::AddLoyaltyPoints
+ end
+ ```
+ </Tab>
+</Tabs>
+
+### Step 3: Add Translations
+
+```yaml config/locales/en.yml
+en:
+ spree:
+ promotion_action_types:
+ add_loyalty_points:
+ name: Add Loyalty Points
+ description: Awards loyalty points to the customer
+```
+
+### Step 4: Restart Your Application
-Coupon codes are generated when a promotion is created. The number of codes to be generated is set in the `number_of_codes` attribute on the `Promotion` object.
+After restarting, the new action will be available in the Admin > Promotions interface.
-Here is a list of attributes for the `CouponCode` model:
+## Promotion Flow
-| Attribute | Description | Example |
-|----------------|-----------------------------------------------------------------------------|---------------|
-| `code` | Auto-generated unique 16-character code for the promotion. | `22A0F62A230BD919` |
-| `promotion_id` | ID of the associated promotion. | `12345` |
-| `order_id` | ID of the order to which the coupon code is applied. | `67890` |
-| `state` | Sate of the promotion code | `unused`, `used` |
+Understanding how promotions are evaluated and applied:
-If `code_prefix` is set in the `Promotion` object (eg. `PRM`), the `code` will be generated with that prefix, eg. `PRM22A0F62A230BD919`.
+1. **Order Update** - When an order is updated, the system checks all eligible promotions
+2. **Eligibility Check** - For each promotion:
+ - Check if within `starts_at` and `expires_at` range
+ - Check if under `usage_limit`
+ - Evaluate all rules based on `match_policy` (all or any)
+3. **Action Execution** - If eligible, each action's `perform()` method is called
+4. **Tracking** - Applied promotions are recorded in `spree_order_promotions`
+5. **Re-evaluation** - Eligibility is re-checked on every order update; adjustments from ineligible promotions are removed
-## Extending Promotions
+## Related Documentation
-Please follow our [extending Promotions guide](/developer/extending-spree/promotions) to learn how to create custom promotion rules and actions.
\ No newline at end of file
+- [Calculators](/developer/core-concepts/calculators) - Learn about promotion calculators
+- [Orders](/developer/core-concepts/orders) - Understanding order processing
+- [Customization Quickstart](/developer/customization/quickstart) - Overview of customization options
diff --git a/docs/developer/core-concepts/search-filtering.mdx b/docs/developer/core-concepts/search-filtering.mdx
index d8c4fe7b3d..176bf32d15 100644
--- a/docs/developer/core-concepts/search-filtering.mdx
+++ b/docs/developer/core-concepts/search-filtering.mdx
@@ -577,3 +577,9 @@ products?q[in_stock]=true
- [Ransack Search Matchers](https://activerecord-hackery.github.io/ransack/getting-started/search-matches/)
- [Platform API Documentation](/developer/api/v2/platform)
+
+## Related Documentation
+
+- [Admin Tables](/developer/admin/tables) - Customize admin list views with sorting and filtering
+- [Decorators](/developer/customization/decorators) - Add searchable attributes without decorators
+- [Customization Quickstart](/developer/customization/quickstart) - Overview of all customization options
diff --git a/docs/developer/core-concepts/shipments.mdx b/docs/developer/core-concepts/shipments.mdx
index a2ac45f3a7..dfc97fcc68 100644
--- a/docs/developer/core-concepts/shipments.mdx
+++ b/docs/developer/core-concepts/shipments.mdx
@@ -4,6 +4,74 @@ title: Shipments
## Overview
+### Shipment Model Diagram
+
+```mermaid
+erDiagram
+ Shipment {
+ string number
+ string tracking
+ string state
+ decimal cost
+ datetime shipped_at
+ }
+
+ ShippingMethod {
+ string name
+ string display_on
+ string tracking_url
+ integer position
+ }
+
+ ShippingCategory {
+ string name
+ }
+
+ ShippingRate {
+ decimal cost
+ boolean selected
+ }
+
+ Zone {
+ string name
+ string description
+ string kind
+ }
+
+ InventoryUnit {
+ string state
+ }
+
+ StockLocation {
+ string name
+ boolean active
+ boolean default
+ }
+
+ Order ||--o{ Shipment : "has many"
+ Shipment ||--o{ ShippingRate : "has many"
+ Shipment ||--o{ InventoryUnit : "has many"
+ Shipment }o--|| StockLocation : "ships from"
+ Shipment }o--|| ShippingMethod : "selected method"
+ Shipment ||--o{ Adjustment : "has many"
+ ShippingMethod ||--o{ ShippingRate : "has many"
+ ShippingMethod }o--o{ Zone : "serves"
+ ShippingMethod }o--o{ ShippingCategory : "handles"
+ ShippingMethod ||--|| Calculator : "has one"
+ ShippingMethod }o--o{ Store : "available in"
+ Product }o--|| ShippingCategory : "belongs to"
+ Variant ||--o{ InventoryUnit : "has many"
+ StockLocation ||--o{ StockItem : "has many"
+```
+
+**Key relationships:**
+- **Shipment** tracks delivery of items from a [Stock Location](/developer/core-concepts/inventory#stock-locations)
+- **Shipping Method** defines the carrier/service (UPS, FedEx, etc.)
+- **Shipping Rate** represents the calculated cost for a method
+- **[Zone](/developer/core-concepts/addresses#zones)** defines geographic regions for shipping availability
+- **Shipping Category** groups products with similar shipping requirements
+- **Inventory Units** track individual items within each shipment
+
This guide explains how Spree represents shipping options and how it calculates expected costs, and shows how you can configure the system with your own shipping methods. After reading it you should know:
* how shipments and shipping are implemented in Spree
@@ -24,7 +92,7 @@ Shipments have the following attributes:
| `tracking` | The identifier given for the shipping provider i.e. FedEx, UPS, etc. | 1Z999AA10123456784 |
| `shipped_at` | The time when the shipment was shipped. | 2021-07-21T14:36:00.000Z |
| `state` | The current state of the shipment. | `shipped` |
-| `stock_location_id`| The ID of the Stock Location where the items for this shipment will be sourced from. | 3 |
+| `stock_location_id`| The ID of the [Stock Location](/developer/core-concepts/inventory#stock-locations) where the items for this shipment will be sourced from. | 3 |
A shipment can go through many different states, as illustrated below.
@@ -64,7 +132,7 @@ and their pricing is as follow:
To achieve this setup you need the following configuration:
* Shipping Categories: All your products are the same, so you only need to define one default shipping category. Each of your products would then need to be assigned to this shipping category.
-* 1 Stock Location: You are shipping all items from the same location, so you can use the default.
+* 1 [Stock Location](/developer/core-concepts/inventory#stock-locations): You are shipping all items from the same location, so you can use the default.
* 2 Shipping Methods Configuration-&gt;Shipping Methods as follows:
| Name | Zone | Calculator |
@@ -74,7 +142,7 @@ To achieve this setup you need the following configuration:
### Advanced Setup
-Consider you sell products to a single zone US and you ship from 2 locations Stock Locations:
+Consider you sell products to a single zone US and you ship from 2 [Stock Locations](/developer/core-concepts/inventory#stock-locations):
* New York
* Los Angeles
@@ -113,7 +181,7 @@ To achieve this setup you need the following configuration:
* 4 Shipping Categories: Default, Light, Regular and Heavy
* 3 Shipping Methods Configuration-&gt;Shipping Methods: FedEx, DHL, USPS
-* 2 Stock Locations Configuration-&gt;Stock Locations: New York, Los Angeles
+* 2 [Stock Locations](/developer/core-concepts/inventory#stock-locations) (Configuration -> Stock Locations): New York, Los Angeles
| S. Category / S. Method | DHL | FedEx | USPS |
| ---: | ---: | ---: | ---: |
@@ -293,13 +361,13 @@ This section describes the four main components that power split shipments: [The
### The Coordinator
-The `Spree::Stock::Coordinator` is the starting point for determining shipments when calling `create_proposed_shipments` on an order. Its job is to go through each `StockLocation` available and determine what can be shipped from that location.
+The `Spree::Stock::Coordinator` is the starting point for determining shipments when calling `create_proposed_shipments` on an order. Its job is to go through each [Stock Location](/developer/core-concepts/inventory#stock-locations) available and determine what can be shipped from that location.
The `Spree::Stock::Coordinator` will ultimately return an array of packages which can then be easily converted into shipments for an order by calling `to_shipment` on them.
### The Packer
-A `Spree::Stock::Packer` object is an important part of the `create_proposed_shipments` process. Its job is to determine possible packages for a given StockLocation and order. It uses rules defined in classes known as `Splitters` to determine what packages can be shipped from a `StockLocation`.
+A `Spree::Stock::Packer` object is an important part of the `create_proposed_shipments` process. Its job is to determine possible packages for a given [Stock Location](/developer/core-concepts/inventory#stock-locations) and order. It uses rules defined in classes known as `Splitters` to determine what packages can be shipped from a [Stock Location](/developer/core-concepts/inventory#stock-locations).
For example, we may have two splitters for a stock location. One splitter has a rule that any order weighing more than 50lbs should be shipped in a separate package from items weighing less. Our other splitter is a catch-all for any item weighing less than 50lbs. So, given one item in an order weighing 60lbs and two items weighing less, the Packer would use the rules defined in our splitters to come up with two separate packages: one containing the single 60lb item, the other containing our other two items.
@@ -309,14 +377,13 @@ Spree comes with two default splitters which are run in sequence. This means tha
Let's take a look at what the default splitters do:
-<AccordionGroup>
- <Accordion title="Shipping Category Splitter">
- Splits an order into packages based on items' shipping categories. This means that each package will only have items that all belong to the same shipping category.
- </Accordion>
- <Accordion title="Weight Splitter">
- Splits an order into packages based on a weight threshold. This means that each package has a mass weight. If a new item is added to the order and it causes a package to go over the weight threshold, a new package will be created so that all packages weigh less than the threshold. You can set the weight threshold by changing <code>Spree::Stock::Splitter::Weight.threshold</code> (defaults to <code>150</code>) in an initializer.
- </Accordion>
-</AccordionGroup>
+**Shipping Category Splitter**
+
+Splits an order into packages based on items' shipping categories. This means that each package will only have items that all belong to the same shipping category.
+
+**Weight Splitter**
+
+Splits an order into packages based on a weight threshold. This means that each package has a mass weight. If a new item is added to the order and it causes a package to go over the weight threshold, a new package will be created so that all packages weigh less than the threshold. You can set the weight threshold by changing `Spree::Stock::Splitter::Weight.threshold` (defaults to `150`) in an initializer.
#### Custom Splitters
@@ -329,7 +396,9 @@ After creating your splitter, you need to add it to the array of splitters Spree
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.stock_splitters << Spree::Stock::Splitter::CustomSplitter
+ Rails.application.config.after_initialize do
+ Spree.stock_splitters << Spree::Stock::Splitter::CustomSplitter
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
@@ -346,10 +415,12 @@ You can also completely override the splitters used in Spree, rearrange them, et
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.stock_splitters = [
- Spree::Stock::Splitter::CustomSplitter,
- Spree::Stock::Splitter::ShippingCategory
- ]
+ Rails.application.config.after_initialize do
+ Spree.stock_splitters = [
+ Spree::Stock::Splitter::CustomSplitter,
+ Spree::Stock::Splitter::ShippingCategory
+ ]
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
@@ -369,17 +440,21 @@ Or if you don't want to split packages just set the option above to an empty arr
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.stock_splitters = []
+ Rails.application.config.after_initialize do
+ Spree.stock_splitters = []
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
```ruby config/initializers/spree.rb
- Rails.application.config.spree.stock_splitters = []
+ Rails.application.config.after_initialize do
+ Rails.application.config.spree.stock_splitters = []
+ end
```
</Tab>
</Tabs>
-If you want to add different splitters for each `StockLocation`, you need to decorate the `Spree::Stock::Coordinator` class and override the `splitters` method.
+If you want to add different splitters for each [Stock Location](/developer/core-concepts/inventory#stock-locations), you need to decorate the `Spree::Stock::Coordinator` class and override the `splitters` method.
### The Prioritizer
@@ -394,12 +469,18 @@ The prioritizer is also a customization point. If you want to customize which pa
The `Adjuster` visits each package in an order and ensures the correct number of items are in each package. To customize this functionality, you need to do two things:
1. Subclass the [Spree::Stock::Adjuster](https://github.com/spree/spree/blob/main/core/app/models/spree/stock/adjuster.rb) class and override the the `adjust` method to get the desired functionality.
-2. Decorate the `Spree::Stock::Coordinator` and override the `prioritize_packages` method, passing in your custom adjuster class to the `Prioritizer` initializer. For example, if our adjuster was called `Spree::Stock::CustomAdjuster`, we would do the following in `app/models/spree/stock/coordinator_decorator.rb`:
+2. Override the `prioritize_packages` method in the `Spree::Stock::Coordinator`, passing in your custom adjuster class to the `Prioritizer` initializer.
+
+<Warning>
+ Decorators should be used as a last resort as they can make upgrades difficult. See [Decorators](/developer/customization/decorators) for more information and alternatives.
+</Warning>
+
+For example, if your adjuster was called `Spree::Stock::CustomAdjuster`, you would do the following in `app/models/spree/stock/coordinator_decorator.rb`:
```ruby app/models/spree/stock/coordinator_decorator.rb
module Spree
module Stock
- module CoordinatorDecorator do
+ module CoordinatorDecorator
def prioritize_packages(packages)
prioritizer = Prioritizer.new(order, packages, Spree::Stock::CustomAdjuster)
prioritizer.prioritized_packages
@@ -415,3 +496,11 @@ end
The `Spree::Stock::Estimator` loops through the packages created by the packer in order to calculate and attach shipping rates to them. This information is then returned to the user so they can select shipments for their order and complete the checkout process.
+## Related Documentation
+
+- [Orders](/developer/core-concepts/orders) - Order management and state machine
+- [Inventory](/developer/core-concepts/inventory) - Stock locations and inventory management
+- [Calculators](/developer/core-concepts/calculators) - Shipping rate calculators
+- [Addresses](/developer/core-concepts/addresses) - Shipping address and zones
+- [Events](/developer/core-concepts/events) - Subscribe to shipment events
+
diff --git a/docs/developer/core-concepts/stores.mdx b/docs/developer/core-concepts/stores.mdx
index ed363b8bc8..08383b0c27 100644
--- a/docs/developer/core-concepts/stores.mdx
+++ b/docs/developer/core-concepts/stores.mdx
@@ -14,6 +14,70 @@ The `Spree::Store` model is the center of the Spree ecosystem. Each Spree instal
![](/images/mulit_store_978x2.png)
</Frame>
+### Store Model Diagram
+
+```mermaid
+erDiagram
+ Store {
+ string name
+ string code
+ string url
+ string default_currency
+ string supported_currencies
+ string default_locale
+ string supported_locales
+ boolean default
+ string mail_from_address
+ string customer_support_email
+ }
+
+ Order {
+ string number
+ string currency
+ string state
+ decimal total
+ }
+
+ Product {
+ string name
+ string status
+ datetime available_on
+ }
+
+ PaymentMethod {
+ string name
+ string type
+ boolean active
+ string display_on
+ }
+
+ ShippingMethod {
+ string name
+ string display_on
+ }
+
+ Taxonomy {
+ string name
+ integer position
+ }
+
+ Store ||--o{ Order : "has many"
+ Store }o--o{ Product : "has many"
+ Store }o--o{ PaymentMethod : "has many"
+ Store }o--o{ ShippingMethod : "has many"
+ Store ||--o{ StockLocation : "has many"
+ Store ||--o{ Taxonomy : "has many"
+ Store ||--o{ Menu : "has many"
+ Store ||--o{ CmsPage : "has many"
+ Store ||--o{ WebhookEndpoint : "has many"
+```
+
+**Key relationships:**
+- **Store** is the central model - all commerce data is scoped to a store
+- Each store has its own [Orders](/developer/core-concepts/orders), [Products](/developer/core-concepts/products), [Payment Methods](/developer/core-concepts/payments), and [Shipping Methods](/developer/core-concepts/shipments)
+- Stores can have different currencies, locales, and configurations
+- Content (Menus, CMS Pages) and [Webhooks](/developer/core-concepts/webhooks) are also store-specific
+
### Store attributes
| Attribute | Description | Example Value |
diff --git a/docs/developer/core-concepts/taxes.mdx b/docs/developer/core-concepts/taxes.mdx
index e37e2b9eea..72ce40b9e3 100644
--- a/docs/developer/core-concepts/taxes.mdx
+++ b/docs/developer/core-concepts/taxes.mdx
@@ -3,9 +3,70 @@ title: Taxes
description: Learn how to configure taxes in Spree
---
+## Overview
+
+Spree represents taxes for an order by using Tax Categories and Tax Rates.
+
+### Tax Model Diagram
+
+```mermaid
+erDiagram
+ TaxCategory {
+ string name
+ boolean is_default
+ string tax_code
+ string description
+ }
+
+ TaxRate {
+ string name
+ decimal amount
+ boolean included_in_price
+ boolean show_rate_in_label
+ }
+
+ Zone {
+ string name
+ string description
+ boolean default_tax
+ string kind
+ }
+
+ ZoneMember {
+ string zoneable_type
+ integer zoneable_id
+ }
+
+ Adjustment {
+ decimal amount
+ string label
+ boolean included
+ boolean eligible
+ string state
+ }
+
+ TaxCategory ||--o{ TaxRate : "has many"
+ TaxCategory ||--o{ Product : "has many"
+ TaxCategory ||--o{ ShippingMethod : "has many"
+ TaxRate }o--|| Zone : "belongs to"
+ TaxRate }o--|| TaxCategory : "belongs to"
+ TaxRate ||--|| Calculator : "has one"
+ TaxRate ||--o{ Adjustment : "creates"
+ Zone ||--o{ ZoneMember : "has many"
+ ZoneMember }o--o| Country : "member"
+ ZoneMember }o--o| State : "member"
+```
+
+**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
+- **[Calculator](/developer/core-concepts/calculators)** computes the tax amount
+- **[Adjustments](/developer/core-concepts/adjustments)** are created on orders/line items to apply taxes
+## Tax Categories and Rates
-Spree represents taxes for an order by using Tax Categories and `tax_rates`.
+Spree represents taxes for an order by using Tax Categories and Tax Rates.
Products within Spree can be linked to Tax Categories, which are then used to influence the taxation rate for the products when they are purchased. One Tax Category can be set to being the default for the entire system, which means that if a product doesn't have a related tax category, then this default tax category would be used.
@@ -96,7 +157,7 @@ If the customer purchases a single clothing item for $17.99 and they live in the
The sales tax calculation is $17.99 x 5% for a total tax of $0.8995, which is rounded up to two decimal places, to $0.90. This tax amount is then applied to the order as an adjustment.
- See the \[Adjustments Guide\]/developer/core-concepts/adjustments.html if you need more information on adjustments.
+See the [Adjustments Guide](/developer/core-concepts/adjustments) if you need more information on adjustments.
If the quantity of the item is changed to 2, then the tax amount doubles: $17.99 x 2 x 0.05 is $1.799, which is again rounded up to two decimal places, applying a tax adjustment of $1.80.
@@ -142,4 +203,11 @@ As of January 1st, 2015, digital products sold within the EU must have the VAT o
If you change the tax zone of the current order by changing the relevant address, prices will now be shown and used including the correct VAT for the current order.
- All of the examples in this guide are meant to be used for illustrative purposes. They are not meant to be used as definitive interpretations of tax law. You should consult your accountant or attorney for guidance on how much tax to collect and under what circumstances.
\ No newline at end of file
+All of the examples in this guide are meant to be used for illustrative purposes. They are not meant to be used as definitive interpretations of tax law. You should consult your accountant or attorney for guidance on how much tax to collect and under what circumstances.
+
+## Related Documentation
+
+- [Addresses](/developer/core-concepts/addresses) - Zones and address-based taxation
+- [Adjustments](/developer/core-concepts/adjustments) - Tax adjustments
+- [Calculators](/developer/core-concepts/calculators) - Tax rate calculators
+- [Orders](/developer/core-concepts/orders) - How taxes affect order totals
\ No newline at end of file
diff --git a/docs/developer/core-concepts/users.mdx b/docs/developer/core-concepts/users.mdx
index 76f74ae061..3bfa8ea2f0 100644
--- a/docs/developer/core-concepts/users.mdx
+++ b/docs/developer/core-concepts/users.mdx
@@ -89,3 +89,10 @@ In all Spree controllers or any controller inheriting from `Spree::BaseControlle
```ruby
spree_current_user
```
+
+## Related Documentation
+
+- [Addresses](/developer/core-concepts/addresses) - User address management
+- [Orders](/developer/core-concepts/orders) - User order history
+- [Authentication](/developer/customization/authentication) - Custom authentication
+- [Permissions](/developer/customization/permissions) - User permissions and authorization
diff --git a/docs/developer/core-concepts/webhooks.mdx b/docs/developer/core-concepts/webhooks.mdx
index 133105f460..cb88724647 100644
--- a/docs/developer/core-concepts/webhooks.mdx
+++ b/docs/developer/core-concepts/webhooks.mdx
@@ -359,4 +359,5 @@ delivery.response_body # => Response from your endpoint
## Related Documentation
- [Events](/developer/core-concepts/events) - Understanding Spree's event system
+- [Customization Quickstart](/developer/customization/quickstart) - Overview of all customization options
- [Dependencies](/developer/customization/dependencies) - Customizing Spree services
diff --git a/docs/developer/customization/checkout.mdx b/docs/developer/customization/checkout.mdx
index e917f579e3..8324a5b903 100644
--- a/docs/developer/customization/checkout.mdx
+++ b/docs/developer/customization/checkout.mdx
@@ -96,9 +96,38 @@ This step is disabled by default, but can be enabled by two ways:
## Adding Logic Before or After a Particular Step
-The [state_machines](https://github.com/state-machines/state_machines) gem allows you to implement callbacks before or after transitioning to a particular step. These callbacks work similarly to [Active Record Callbacks](http://guides.rubyonrails.org/active_record_callbacks.html) in that you can specify a method or block of code to be executed prior to or after a transition. If the method executed in a before_transition returns false, then the transition will not execute.
+There are two approaches for adding logic around checkout state transitions:
-So, for example, if you wanted to verify that the user provides a valid zip code before transitioning to the delivery step, you would first implement a `valid_zip_code?` method, and then tell the state machine to run this method before that transition, placing this code in a file called `app/models/spree/order_decorator.rb`:
+### Approach 1: Events Subscribers (Recommended for side effects)
+
+For actions that should happen **after** a checkout step completes (syncing with external services, sending notifications, logging, etc.), use [Events subscribers](/developer/core-concepts/events). This is the recommended approach because it keeps your code decoupled from Spree internals.
+
+```ruby app/subscribers/my_app/order_completed_subscriber.rb
+module MyApp
+ class OrderCompletedSubscriber < Spree::Subscriber
+ subscribes_to 'order.completed'
+
+ def handle(event)
+ order = Spree::Order.find_by(id: event.payload['id'])
+ return unless order
+
+ # Sync to fulfillment system, notify warehouse, etc.
+ FulfillmentService.notify(order)
+ AnalyticsService.track_purchase(order)
+ end
+ end
+end
+```
+
+<Info>
+ Events are fired automatically when orders change state. See [Events documentation](/developer/core-concepts/events#order-events) for all available order events.
+</Info>
+
+### Approach 2: State Machine Callbacks (For validation/blocking logic)
+
+The [state_machines](https://github.com/state-machines/state_machines) gem allows you to implement callbacks that can **block** transitions. Use this approach only when you need to prevent a transition based on validation logic.
+
+For example, if you wanted to verify that the user provides a valid zip code before transitioning to the delivery step:
```ruby app/models/spree/order_decorator.rb
module Spree
@@ -106,9 +135,10 @@ module Spree
def self.prepended(base)
base.state_machine.before_transition to: :delivery, do: :valid_zip_code?
end
-
+
def valid_zip_code?
- # logic to check if the zip code is valid
+ # Return false to prevent the transition
+ ship_address&.zipcode&.match?(/^\d{5}(-\d{4})?$/)
end
end
@@ -118,6 +148,10 @@ end
This callback would prevent transitioning to the `delivery` step if `valid_zip_code?` returns false.
+<Warning>
+ Avoid using state machine callbacks for side effects like API calls or notifications. These can slow down checkout and may fail silently. Use [Events subscribers](/developer/core-concepts/events) instead.
+</Warning>
+
## Modifying the checkout flow
To add or remove steps to the checkout flow, you can use the
diff --git a/docs/developer/customization/decorators.mdx b/docs/developer/customization/decorators.mdx
index dd172ba80c..a35b46863e 100644
--- a/docs/developer/customization/decorators.mdx
+++ b/docs/developer/customization/decorators.mdx
@@ -3,8 +3,37 @@ title: Decorators
description: Decorators allow you to add or modify behavior of Spree classes in your application.
---
+<Warning>
+ **Decorators should be a last resort.** They tightly couple your code to Spree internals and can break during upgrades. Before using decorators, consider these modern alternatives that are safer and easier to maintain:
+
+ - **[Events & Subscribers](/developer/core-concepts/events)** - For reacting to model changes (after save, create, update, delete)
+ - **[Webhooks](/developer/core-concepts/webhooks)** - For notifying external services when events occur
+ - **[Dependencies](/developer/customization/dependencies)** - For swapping out services, serializers, and abilities
+ - **[Admin Navigation](/developer/admin/navigation)** - For adding menu items without controller decorators
+ - **[Admin Partials](/developer/admin/extending-ui)** - For extending admin UI without view decorators
+ - **[Admin Tables](/developer/admin/tables)** - For customizing admin list views
+ - **[Ransack Configuration](/developer/core-concepts/search-filtering#extending-ransackable-configuration)** - For adding searchable/sortable fields without model decorators
+</Warning>
+
+## When to Use Decorators vs Modern Alternatives
+
+Before reaching for a decorator, check if your use case is better served by a modern alternative:
+
+| Use Case | Instead of Decorator | Use This |
+|----------|---------------------|----------|
+| After-save hooks (sync to external service) | Model decorator with `after_save` | [Events subscriber](/developer/core-concepts/events) |
+| Notify external service on changes | Model decorator with callbacks | [Webhooks](/developer/core-concepts/webhooks) |
+| Custom add-to-cart logic | Service decorator | [Dependencies injection](/developer/customization/dependencies) |
+| Custom API responses | Serializer decorator | [Dependencies injection](/developer/customization/dependencies) |
+| Add admin menu item | Controller decorator | [Admin Navigation API](/developer/admin/navigation) |
+| Add section to admin form | View decorator/override | [Admin Partials injection](/developer/admin/extending-ui) |
+| Add searchable/filterable field | Model decorator with `ransackable_attributes` | [Ransack configuration](/developer/core-concepts/search-filtering#extending-ransackable-configuration) |
+| Add association to core model | - | Decorator (still appropriate) |
+| Add validation to core model | - | Decorator (still appropriate) |
+| Add new method to core model | - | Decorator (still appropriate) |
+
<Info>
- Decorators should be used as a last resort. They make upgrades difficult. Please use [Spree Dependencies](/developer/customization/dependencies) if possible.
+ Decorators are still appropriate for **structural changes** like adding associations, validations, scopes, and new methods to models. Use modern alternatives for **behavioral changes** like callbacks, hooks, and side effects.
</Info>
## Overview
@@ -196,36 +225,6 @@ module Spree
end
```
-### Adding Callbacks
-
-```ruby app/models/spree/product_decorator.rb
-module Spree
- module ProductDecorator
- def self.prepended(base)
- base.before_validation :normalize_name
- base.after_save :sync_to_external_service
- base.after_destroy :cleanup_external_data
- end
-
- private
-
- def normalize_name
- self.name = name.strip.titleize if name.present?
- end
-
- def sync_to_external_service
- ExternalSyncJob.perform_later(self) if saved_change_to_name?
- end
-
- def cleanup_external_data
- ExternalCleanupJob.perform_later(id)
- end
- end
-
- Product.prepend(ProductDecorator)
-end
-```
-
### Adding Class Methods
Use `extend` within the `prepended` callback to add class methods:
@@ -256,7 +255,39 @@ Spree::Product.search_by_name('shirt')
## Decorating Controllers
-### Adding a New Action
+<Warning>
+ **Consider creating a new controller instead of decorating.** Creating your own controller that inherits from Spree's base controllers is more maintainable and less likely to break during upgrades. Use controller decorators only when you must modify existing Spree actions.
+</Warning>
+
+### Recommended: Create a New Controller
+
+Instead of decorating `Spree::ProductsController` to add a new action, create your own controller:
+
+```ruby app/controllers/spree/product_quick_views_controller.rb
+module Spree
+ class ProductQuickViewsController < StoreController
+ def show
+ @product = current_store.products.friendly.find(params[:product_id])
+ render partial: 'spree/products/quick_view', locals: { product: @product }
+ end
+ end
+end
+```
+
+```ruby config/routes.rb
+Spree::Core::Engine.add_routes do
+ get 'products/:product_id/quick_view', to: 'product_quick_views#show', as: :product_quick_view
+end
+```
+
+This approach:
+- Won't break when Spree updates `ProductsController`
+- Is easier to test in isolation
+- Makes your customizations clearly visible in your codebase
+
+### Adding a New Action via Decorator
+
+If you must add an action to an existing controller:
```ruby app/controllers/spree/products_controller_decorator.rb
module Spree
@@ -293,6 +324,10 @@ end
### Modifying Existing Actions
+<Warning>
+ **High risk of breaking during upgrades.** When you override an existing Spree action, your code depends on Spree's internal implementation details. If Spree changes the action's behavior, instance variables, or method signatures in a future version, your decorator may silently break or cause unexpected bugs. Use [Events](/developer/core-concepts/events) for post-action side effects instead.
+</Warning>
+
```ruby app/controllers/spree/admin/products_controller_decorator.rb
module Spree
module Admin
@@ -324,6 +359,10 @@ module Spree
end
```
+<Info>
+ **Better alternative:** For post-action side effects like notifications, use [Events subscribers](/developer/core-concepts/events) instead. Subscribe to `product.created` to be notified when products are created, without coupling to controller internals.
+</Info>
+
### Adding Before Actions
```ruby app/controllers/spree/checkout_controller_decorator.rb
@@ -434,8 +473,79 @@ def self.prepended(base)
end
```
+## Migrating from Decorators to Modern Patterns
+
+If you have existing decorators that use callbacks for side effects, consider migrating them to Events subscribers for better maintainability.
+
+### Example: Migrating an After-Save Callback
+
+**Before (Decorator with callback):**
+
+```ruby app/models/spree/product_decorator.rb
+module Spree
+ module ProductDecorator
+ def self.prepended(base)
+ base.after_save :sync_to_external_service
+ end
+
+ private
+
+ def sync_to_external_service
+ ExternalSyncJob.perform_later(self) if saved_change_to_name?
+ end
+ end
+
+ Product.prepend(ProductDecorator)
+end
+```
+
+**After (Events subscriber):**
+
+```ruby app/subscribers/my_app/product_sync_subscriber.rb
+module MyApp
+ class ProductSyncSubscriber < Spree::Subscriber
+ subscribes_to 'product.updated'
+
+ def handle(event)
+ product = Spree::Product.find_by(id: event.payload['id'])
+ return unless product
+
+ # The payload includes changes, check if name changed
+ if event.payload['previous_changes']&.key?('name')
+ ExternalSyncJob.perform_later(product)
+ end
+ end
+ end
+end
+```
+
+### Benefits of Migration
+
+<CardGroup cols={2}>
+ <Card title="Loose coupling" icon="link-slash">
+ Your code doesn't depend on Spree internals. Events provide a stable interface.
+ </Card>
+
+ <Card title="Easier upgrades" icon="arrow-up">
+ Events-based code is less likely to break when Spree is updated.
+ </Card>
+
+ <Card title="Better testability" icon="flask-vial">
+ Subscribers can be tested in isolation without loading the full model.
+ </Card>
+
+ <Card title="Async by default" icon="bolt">
+ Subscribers run via ActiveJob, keeping your requests fast.
+ </Card>
+</CardGroup>
+
## Related Documentation
+- [Events](/developer/core-concepts/events) - Learn about Spree's event system
+- [Webhooks](/developer/core-concepts/webhooks) - HTTP callbacks for external integrations
+- [Dependencies](/developer/customization/dependencies) - Swap core services with your own
+- [Admin Navigation](/developer/admin/navigation) - Extend admin menu without decorators
+- [Admin Partials](/developer/admin/extending-ui) - Extend admin UI without view decorators
- [Extending Core Models Tutorial](/developer/tutorial/extending-models) - Step-by-step guide to connecting custom models with Spree core
- [Customization Overview](/developer/customization/quickstart) - General customization patterns
- [Logic Customization](/developer/customization/logic) - Customizing business logic
diff --git a/docs/developer/customization/promotions.mdx b/docs/developer/customization/promotions.mdx
deleted file mode 100644
index 3401da43a3..0000000000
--- a/docs/developer/customization/promotions.mdx
+++ /dev/null
@@ -1,193 +0,0 @@
----
-title: Custom Promotions
-description: >-
- In this guide we will show you how to create custom promotion rules and actions in Spree.
----
-
-## Overview
-
-In this guide we will show you how to create custom promotion rules and actions in Spree.
-
-### Custom Promotion Actions
-
-<AccordionGroup>
- <Accordion title="1. Ensure proper directory structure">
- Ensure you have the following directory structure:
- ```bash
- mkdir -p app/models/spree/promotion/actions
- ```
- </Accordion>
-
- <Accordion title="2. Create a new model file">
- Create a new file in `app/models/spree/promotion/actions/` directory
- ```bash
- touch app/models/spree/promotion/actions/my_promotion_action.rb
- ```
- </Accordion>
-
- <Accordion title="3. Implement your own Logic">
- Implement your custom logic in the `perform` method.
- ```ruby
- module Spree
- module Promotion
- module Actions
- class MyPromotionAction < Spree::PromotionAction
- def perform(options={})
- # Implement your custom logic here
- end
- end
- end
- end
- end
- ```
- <Note>
- This class needs to inherit from `Spree::PromotionAction` model.
- </Note>
- <Info>
- You can access promotion information using the `promotion` method within any `Spree::PromotionAction`.
- </Info>
- </Accordion>
-
- <Accordion title="4. Register the New Action">
- Register the new action with Spree.
- Open `config/initializers/spree.rb` and add the following line:
-
- <Tabs>
- <Tab title="Spree 5.2+">
- ```ruby config/initializers/spree.rb
- Spree.promotions.actions << Spree::Promotion::Actions::MyPromotionAction
- ```
- </Tab>
- <Tab title="Spree 5.1 and below">
- ```ruby config/initializers/spree.rb
- Rails.application.config.after_initialize do
- Rails.application.config.spree.promotions.actions << Spree::Promotion::Actions::MyPromotionAction
- end
- ```
- </Tab>
- </Tabs>
-
- Once this has been registered, it will be available within Spree's interface.
- </Accordion>
-
- <Accordion title="5. Add Translations for the Admin Dashboard">
- To provide translations for the interface, you will need to define them within your locale file. For instance, to define English translations for your new promotion action, use this code within `config/locales/en.yml`:
-
- ```yaml
- en:
- spree:
- promotion_action_types:
- my_promotion_action:
- name: My Promotion Action
- description: Performs my promotion action.
- ```
- </Accordion>
-
- <Accordion title="6. Restart Your Application">
- After making these changes, restart your application. Your custom promotion action will now be available within Spree's admin interface, ready for use in your promotions.
- </Accordion>
-</AccordionGroup>
-
-### Custom Promotion Rules
-
-<AccordionGroup>
- <Accordion title="1. Ensure proper directory structure">
- Ensure you have the following directory structure:
- ```bash
- mkdir -p app/models/spree/promotion/rules
- ```
- </Accordion>
-
- <Accordion title="2. Create a new model file">
- Create a new file in `app/models/spree/promotion/rules/` directory:
-
- ```bash
- touch app/models/spree/promotion/rules/my_promotion_rule.rb
- ```
- </Accordion>
-
- <Accordion title="3. Implement your own Logic">
- Implement your logic within this class as shown below:
-
- ```ruby
- module Spree
- class Promotion
- module Rules
- class MyPromotionRule < Spree::PromotionRule
- def applicable?(promotable)
- promotable.is_a?(Spree::Order)
- end
-
- def eligible?(order, options = {})
- # Your custom eligibility logic here
- end
-
- def actionable?(line_item)
- # Your custom actionability logic here
- end
- end
- end
- end
- end
- ```
-
- <Note>
- This class needs to inherit from `Spree::PromotionRule` model.
- </Note>
-
- <Note>
- The <code>eligible?</code> method should return <code>true</code> or <code>false</code> to indicate if the promotion should be eligible for an order, based on your custom logic. Similarly, define <code>actionable?</code> to evaluate line items against your promotion criteria.
- </Note>
- </Accordion>
-
- <Accordion title="4. Register the Custom Rule">
- To make your custom rule available, register it within Spree by adding the following block to your `config/initializers/spree.rb` file:
-
- <Tabs>
- <Tab title="Spree 5.2+">
- ```ruby config/initializers/spree.rb
- Spree.promotions.rules << Spree::Promotion::Rules::MyPromotionRule
- ```
- </Tab>
- <Tab title="Spree 5.1 and below">
- ```ruby config/initializers/spree.rb
- Rails.application.config.after_initialize do
- Rails.application.config.spree.promotions.rules << Spree::Promotion::Rules::MyPromotionRule
- end
- ```
- </Tab>
- </Tabs>
-
- This step ensures that your custom rule is recognized and can be utilized within the Spree ecosystem.
- </Accordion>
-
- <Accordion title="5. Create Promotion Rule view template">
-
- Create a partial for your new rule:
-
- ```bash
- touch app/views/spree/admin/promotions/rules/_my_promotion_rule.html.erb
- ```
-
- This file can either be simple or complex based on whether your rule requires parameters for configuration.
-
- For guidance, refer to existing rule partials in Spree's backend sources to understand how to structure this file.
- </Accordion>
-
- <Accordion title="6. Add Translations for the Admin Dashboard">
- To display your rule within the Spree admin interface, define its name and description in your locale files. For English, edit `config/locales/en.yml` and add:
-
- ```yaml
- en:
- spree:
- promotion_rule_types:
- my_promotion_rule:
- name: "My Promotion Rule"
- description: "Custom rule for my promotion"
- ```
- </Accordion>
-
- <Accordion title="7. Restart Your Application">
- After making these changes, restart your application. Your custom promotion rule will now be available within Spree's admin interface, ready for use in your promotions.
- </Accordion>
-</AccordionGroup>
diff --git a/docs/developer/customization/quickstart.mdx b/docs/developer/customization/quickstart.mdx
index 68f23c0cab..16f9e0e613 100644
--- a/docs/developer/customization/quickstart.mdx
+++ b/docs/developer/customization/quickstart.mdx
@@ -4,15 +4,27 @@ og:title: Spree Customization Quickstart
description: Learn how to customize every part of the Spree stack
---
-Spree is a very flexible platform allowing you to customize every part of it, to suit your business needs.
-
-There are several ways you can achieve this:
+Spree is a flexible platform allowing you to customize every part of it to suit your business needs. This guide presents customization options **in order of recommendation** - start from the top and only move down if simpler options don't meet your needs.
+
+## Quick Reference
+
+| What you want to do | Recommended approach |
+|---------------------|---------------------|
+| Change store settings (currency, zones, languages) | [Store Settings](#store-settings) |
+| Tweak Spree behavior globally | [Configuration](#configuration) |
+| React to model changes (sync, notifications) | [Events & Subscribers](#events-and-subscribers) |
+| Notify external services | [Webhooks](#webhooks) |
+| Swap core services (cart, checkout, etc.) | [Dependencies](#dependencies) |
+| Add admin menu items | [Admin Navigation](#admin-extensions) |
+| Add sections to admin forms | [Admin Partials](#admin-extensions) |
+| Add searchable/filterable fields | [Ransack Configuration](#search-and-filtering) |
+| Add associations/validations to models | [Decorators](#decorators) (last resort) |
<AccordionGroup>
- <Accordion title="Store settings">
- There's a lot of Store settings you can change in the admin panel without touching the code.
+ <Accordion title="Store settings" defaultOpen>
+ **Best for:** Changing currency, shipping zones, languages, and other business settings.
- Changing currency, shipping zones, languages - it's very easy to do.
+ There's a lot of Store settings you can change in the admin panel without touching the code.
Go to **Admin > Settings**
@@ -20,49 +32,164 @@ There are several ways you can achieve this:
</Accordion>
<Accordion title="Configuration">
- Global application configuration allows you to tweak Spree's behavior without having to modify the source code.
+ **Best for:** Tweaking Spree's behavior globally without modifying source code.
+
+ Global application configuration allows you to customize various aspects of Spree:
+
+ ```ruby config/initializers/spree.rb
+ Spree.config do |config|
+ config.allow_guest_checkout = false
+ config.products_per_page = 20
+ end
+ ```
Please see [Configuration](/developer/customization/configuration) section for more information.
</Accordion>
- <Accordion title="Authentication">
- Spree allows you to use your own authentication system.
+ <Accordion title="Events and Subscribers">
+ **Best for:** Reacting to model changes, syncing with external services, sending notifications, audit logging.
- To do this, you need to create a new authentication system and configure Spree to use it.
+ <Info>
+ Events are the **recommended way** to add behavior when something happens in Spree, replacing the need for decorator callbacks.
+ </Info>
- You can find more information in the [Authentication](authentication) section.
+ Spree's event system lets you subscribe to events like `order.completed`, `product.updated`, `payment.paid`, etc.:
+
+ ```ruby app/subscribers/my_app/order_completed_subscriber.rb
+ module MyApp
+ class OrderCompletedSubscriber < Spree::Subscriber
+ subscribes_to 'order.completed'
+
+ def handle(event)
+ order = Spree::Order.find_by(id: event.payload['id'])
+ return unless order
+
+ # Sync to external service, send notification, etc.
+ ExternalService.notify_order_placed(order)
+ end
+ end
+ end
+ ```
+
+ **Key benefits:**
+ - Loose coupling - your code doesn't depend on Spree internals
+ - Async by default - keeps requests fast
+ - Easier testing and upgrades
+
+ Please see [Events](/developer/core-concepts/events) section for more information.
</Accordion>
- <Accordion title="Checkout flow">
- With Spree you can change the checkout flow to fit your business needs.
+ <Accordion title="Webhooks">
+ **Best for:** Notifying external services (ERPs, CRMs, fulfillment systems) when events occur.
- Please see [Checkout flow customization section](checkout) for more information.
+ Webhooks send HTTP POST requests to external URLs when Spree events happen:
+
+ - Order completed → Notify fulfillment system
+ - Product updated → Sync with PIM
+ - Customer created → Add to CRM
+
+ Configure webhooks in **Admin > Developers > Webhooks** or via the API.
+
+ Please see [Webhooks](/developer/core-concepts/webhooks) section for more information.
</Accordion>
<Accordion title="Dependencies">
- Spree allows you to swap core classes and services with your own, eg. you want to handle adding to cart differently.
+ **Best for:** Swapping core services, serializers, and abilities with your own implementations.
- In your `config/initializers/spree.rb` file, you can set the following:
+ Spree allows you to replace core classes without modifying them:
- ```ruby
+ ```ruby config/initializers/spree.rb
Spree::Dependencies.cart_add_item_service = "MyCartAddItemService"
+ Spree::Dependencies.cart_remove_item_service = "MyCartRemoveItemService"
```
- which would use `MyCartAddItemService` to handle adding to cart.
+ This is cleaner than decorating services because you provide a complete replacement rather than patching behavior.
- You can find more information in the [Dependencies](dependencies) section.
+ Please see [Dependencies](dependencies) section for more information.
+ </Accordion>
+
+ <Accordion title="Admin Extensions">
+ **Best for:** Adding menu items, form sections, dashboard widgets, and other UI elements to the admin panel.
+
+ Spree provides declarative APIs for extending the admin without decorators or view overrides:
+
+ **Navigation API** - Add menu items:
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.after_initialize do
+ Spree.admin.navigation.sidebar.add :brands,
+ label: :brands,
+ url: :admin_brands_path,
+ icon: 'award',
+ position: 35
+ end
+ ```
+
+ **Partials API** - Add sections to forms:
+ ```ruby config/initializers/spree.rb
+ Spree.admin.partials.product_form << 'spree/admin/products/erp_section'
+ ```
+
+ Please see:
+ - [Admin Navigation](/developer/admin/navigation) - For adding menu items
+ - [Admin Partials](/developer/admin/extending-ui) - For extending UI
+ - [Admin Tables](/developer/admin/tables) - For customizing list views
+ </Accordion>
+
+ <Accordion title="Search and Filtering">
+ **Best for:** Making custom fields searchable/sortable in the admin and API.
+
+ Instead of decorating models to add `ransackable_attributes`, use the Ransack configuration API:
+
+ ```ruby config/initializers/spree.rb
+ Spree.ransack.add_attribute :product, :erp_id
+ Spree.ransack.add_association :product, :brand
+ ```
+
+ Please see [Search & Filtering](/developer/core-concepts/search-filtering#extending-ransackable-configuration) section for more information.
+ </Accordion>
+
+ <Accordion title="Authentication">
+ **Best for:** Using your own user model or authentication system.
+
+ Spree allows you to use your own authentication system instead of the default Devise-based one.
+
+ You can find more information in the [Authentication](authentication) section.
+ </Accordion>
+
+ <Accordion title="Checkout flow">
+ **Best for:** Customizing checkout steps and flow.
+
+ With Spree you can change the checkout flow to fit your business needs - add steps, remove steps, or change the order.
+
+ Please see [Checkout flow customization section](checkout) for more information.
</Accordion>
<Accordion title="Decorators">
- Decorators allow you to add behavior to Spree classes in your application. We're using a neat feature of Ruby language called [Module.prepend](https://ruby-doc.org/core-2.6.3/Module.html#method-i-prepend) to add the behavior to the model.
+ **Best for:** Adding associations, validations, scopes, and methods to Spree models. Use as a last resort.
+
+ <Warning>
+ Decorators should be used **only when no other option works**. They tightly couple your code to Spree internals and can break during upgrades.
- For example, to add a method that returns the product name in uppercase, you would add the following to your decorator:
+ **Do NOT use decorators for:**
+ - After-save callbacks → Use [Events](/developer/core-concepts/events) instead
+ - External service sync → Use [Webhooks](/developer/core-concepts/webhooks) instead
+ - Custom service logic → Use [Dependencies](dependencies) instead
+ - Admin UI changes → Use [Admin Extensions](#admin-extensions) instead
+ </Warning>
+
+ Decorators are still appropriate for structural changes:
- ```ruby
+ ```ruby app/models/spree/product_decorator.rb
module Spree
module ProductDecorator
- def custom_name
- name.upcase
+ def self.prepended(base)
+ base.belongs_to :brand, class_name: 'MyApp::Brand', optional: true
+ base.validates :external_id, presence: true
+ base.scope :featured, -> { where(featured: true) }
+ end
+
+ def full_title
+ "#{brand&.name} #{name}"
end
end
@@ -70,10 +197,6 @@ There are several ways you can achieve this:
end
```
- <Warning>
- Decorators should be used as a last resort. They can make upgrading Spree more difficult.
- </Warning>
-
Please see [Decorators](decorators) section for more information.
</Accordion>
</AccordionGroup>
diff --git a/docs/developer/storefront/custom-javascript.mdx b/docs/developer/storefront/custom-javascript.mdx
index 96e878e834..a5118f1f5d 100644
--- a/docs/developer/storefront/custom-javascript.mdx
+++ b/docs/developer/storefront/custom-javascript.mdx
@@ -97,7 +97,9 @@ If you need to add a small piece of JavaScript code (eg. tracking, marketing, an
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.storefront.partials.head << 'spree/shared/my_tracking_code'
+ Rails.application.config.after_initialize do
+ Spree.storefront.partials.head << 'spree/shared/my_tracking_code'
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
diff --git a/docs/developer/storefront/pages.mdx b/docs/developer/storefront/pages.mdx
index 435123ced2..272874be32 100644
--- a/docs/developer/storefront/pages.mdx
+++ b/docs/developer/storefront/pages.mdx
@@ -108,7 +108,9 @@ You will need to register the new page in the `config/initializers/spree.rb` fil
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.page_builder.pages << Spree::Pages::PickupLocations
+ Rails.application.config.after_initialize do
+ Spree.page_builder.pages << Spree::Pages::PickupLocations
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
diff --git a/docs/developer/tutorial/extending-models.mdx b/docs/developer/tutorial/extending-models.mdx
index df15a486e2..53d282c308 100644
--- a/docs/developer/tutorial/extending-models.mdx
+++ b/docs/developer/tutorial/extending-models.mdx
@@ -17,6 +17,24 @@ By the end of this tutorial, you'll have:
- A brand selector in the Product admin form
- Understanding of how to safely extend Spree core models
+## Choosing the Right Approach
+
+Before extending Spree models, consider which approach fits your needs best:
+
+| What you need | Recommended approach |
+|---------------|---------------------|
+| Add association (belongs_to, has_many) | **Decorator** (this tutorial) |
+| Add validation or scope | **Decorator** |
+| Add new instance/class method | **Decorator** |
+| React to model changes (after save, etc.) | [Events subscriber](/developer/core-concepts/events) |
+| Sync with external service on changes | [Events](/developer/core-concepts/events) or [Webhooks](/developer/core-concepts/webhooks) |
+| Add searchable/filterable field | [Ransack configuration](/developer/core-concepts/search-filtering#extending-ransackable-configuration) |
+| Add admin UI elements | [Admin Partials](/developer/admin/extending-ui) |
+
+<Info>
+ This tutorial uses **decorators** because we're adding a structural association between models. For behavioral changes like callbacks, prefer [Events](/developer/core-concepts/events) instead - they're easier to test and maintain.
+</Info>
+
## Understanding Decorators
When working with Spree, you'll often need to add functionality to existing models like `Spree::Product` or `Spree::Order`. However, you shouldn't modify these files directly because:
@@ -187,7 +205,9 @@ Register this partial to appear in the product form. Add to your initializer:
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- Spree.admin.partials.product_form_sidebar << 'spree/admin/products/brand_field'
+ Rails.application.config.after_initialize do
+ Spree.admin.partials.product_form_sidebar << 'spree/admin/products/brand_field'
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
@@ -263,13 +283,36 @@ end
#### Adding Callbacks
+<Warning>
+ For callbacks that trigger side effects (syncing to external services, sending notifications, etc.), use [Events subscribers](/developer/core-concepts/events) instead of decorator callbacks. Events are easier to test and won't break during Spree upgrades.
+</Warning>
+
+**Decorator approach** (use only for simple, internal logic):
+
```ruby
def self.prepended(base)
- base.before_save :do_something
+ base.before_save :normalize_name
end
-def do_something
- # Your callback logic
+def normalize_name
+ self.name = name.strip.titleize if name.present?
+end
+```
+
+**Events approach** (recommended for side effects):
+
+```ruby app/subscribers/my_app/product_sync_subscriber.rb
+module MyApp
+ class ProductSyncSubscriber < Spree::Subscriber
+ subscribes_to 'product.updated'
+
+ def handle(event)
+ product = Spree::Product.find_by(id: event.payload['id'])
+ return unless product
+
+ ExternalSyncService.sync(product)
+ end
+ end
end
```
@@ -332,8 +375,10 @@ Spree::PermittedAttributes.product_attributes << :brand_id
<Tabs>
<Tab title="Spree 5.2+">
```ruby config/initializers/spree.rb
- # Add brand field to product form
- Spree.admin.partials.product_form << 'spree/admin/products/brand_field'
+ Rails.application.config.after_initialize do
+ # Add brand field to product form
+ Spree.admin.partials.product_form << 'spree/admin/products/brand_field'
+ end
```
</Tab>
<Tab title="Spree 5.1 and below">
@@ -348,5 +393,8 @@ Spree::PermittedAttributes.product_attributes << :brand_id
- [Model Tutorial](/developer/tutorial/model) - Creating the Brand model
- [Admin Tutorial](/developer/tutorial/admin) - Building the admin interface
+- [Events](/developer/core-concepts/events) - Subscribe to model changes without decorators
+- [Webhooks](/developer/core-concepts/webhooks) - HTTP callbacks for external integrations
+- [Decorators](/developer/customization/decorators) - Full decorator reference
- [Customization Overview](/developer/customization/quickstart) - More customization patterns
- [Products](/developer/core-concepts/products) - Product model documentation
diff --git a/docs/developer/tutorial/introduction.mdx b/docs/developer/tutorial/introduction.mdx
index b7a21ca16a..e8e090f69e 100644
--- a/docs/developer/tutorial/introduction.mdx
+++ b/docs/developer/tutorial/introduction.mdx
@@ -33,7 +33,7 @@ Spree is built on top of [Ruby on Rails framework](https://rubyonrails.org) and
Add logo images with Active Storage
</Card>
<Card title="5. Extending Core Models" icon="plug" href="/developer/tutorial/extending-models">
- Connect Brands to Products using decorators
+ Connect Brands to Products using associations
</Card>
<Card title="6. Storefront" icon="store" href="/developer/tutorial/storefront">
Create customer-facing brand pages
diff --git a/docs/developer/upgrades/4.10-to-5.0.mdx b/docs/developer/upgrades/4.10-to-5.0.mdx
index 068a28c220..f091bd0e11 100644
--- a/docs/developer/upgrades/4.10-to-5.0.mdx
+++ b/docs/developer/upgrades/4.10-to-5.0.mdx
@@ -25,112 +25,108 @@ Before upgrading, please ensure you have the following prerequisites:
## Upgrade steps
-<AccordionGroup>
- <Accordion title="1. Remove old frontend/backend Spree gems">
+### 1. Remove old frontend/backend Spree gems
- ```bash
- bundle remove spree_auth_devise spree_backend spree_frontend
- ```
- <Warning>
- Remove any code referencing `Spree::Backend`, `Spree::Fronted` or `Spree::Auth` from your application, especially from `config/initializers/spree.rb`.
- </Warning>
- </Accordion>
+```bash
+bundle remove spree_auth_devise spree_backend spree_frontend
+```
- <Accordion title="2. Update main Spree gem">
+<Warning>
+ Remove any code referencing `Spree::Backend`, `Spree::Fronted` or `Spree::Auth` from your application, especially from `config/initializers/spree.rb`.
+</Warning>
- ```bash
- bundle update spree
- ```
- </Accordion>
+### 2. Update main Spree gem
- <Accordion title="2. Install and run missing migrations">
+```bash
+bundle update spree
+```
- ```bash
- bin/rake spree:install:migrations && bin/rails db:migrate
- ```
- </Accordion>
+### 3. Install and run missing migrations
- <Accordion title="3. Add new Spree gems">
+```bash
+bin/rake spree:install:migrations && bin/rails db:migrate
+```
- ```bash
- bundle add spree_storefront spree_admin spree_stripe
- ```
+### 4. Add new Spree gems
- And run the following generators:
+```bash
+bundle add spree_storefront spree_admin spree_stripe
+```
- ```bash
- bin/rails g spree:storefront:install
- bin/rails g spree:admin:install
- bin/rails g spree_stripe:install
- ```
- </Accordion>
+And run the following generators:
- <Accordion title="4. Migrate from Spree Auth Devise gem">
- If you previously used the `spree_auth_devise` gem, you will need to run some commands to create User and connect it to Spree. We don't use the `spree_auth_devise` gem anymore to allow you more control over the authentication and access to all Devise options directly in your application.
+```bash
+bin/rails g spree:storefront:install
+bin/rails g spree:admin:install
+bin/rails g spree_stripe:install
+```
- First, install Devise and run the Devise generator:
+### 5. Migrate from Spree Auth Devise gem
- ```bash
- bundle add devise
- bin/rails g devise:install
- ```
+If you previously used the `spree_auth_devise` gem, you will need to run some commands to create User and connect it to Spree. We don't use the `spree_auth_devise` gem anymore to allow you more control over the authentication and access to all Devise options directly in your application.
- Create `Spree::User` model:
+First, install Devise and run the Devise generator:
- ```bash
- mkdir -p app/models/spree && touch app/models/spree/user.rb
- ```
+```bash
+bundle add devise
+bin/rails g devise:install
+```
- Add the following code to your `Spree::User` model:
+Create `Spree::User` model:
- ```ruby
- module Spree
- class User < ApplicationRecord
- devise :database_authenticatable # if you want to use the database_authenticatable feature
- devise :recoverable # if you want to use the recoverable feature
- devise :registerable # if you want to use the registerable feature
- devise :confirmable # if you want to use the confirmable feature
- devise :validatable # if you want to use the validatable feature
+```bash
+mkdir -p app/models/spree && touch app/models/spree/user.rb
+```
- devise :rememberable, :trackable, :encryptable, encryptor: 'authlogic_sha512'
+Add the following code to your `Spree::User` model:
- acts_as_paranoid
- end
- end
- ```
+```ruby
+module Spree
+ class User < ApplicationRecord
+ devise :database_authenticatable # if you want to use the database_authenticatable feature
+ devise :recoverable # if you want to use the recoverable feature
+ devise :registerable # if you want to use the registerable feature
+ devise :confirmable # if you want to use the confirmable feature
+ devise :validatable # if you want to use the validatable feature
- In you `config/initializers/spree.rb` file, add the following code:
+ devise :rememberable, :trackable, :encryptable, encryptor: 'authlogic_sha512'
- ```ruby
- Spree.user_class = "Spree::User"
- ```
+ acts_as_paranoid
+ end
+end
+```
- Now run the new authentication generator to connect your `Spree::User` model to Spree:
+In you `config/initializers/spree.rb` file, add the following code:
- ```bash
- bin/rails g spree:authentication:devise
- ```
+```ruby
+Spree.user_class = "Spree::User"
+```
- And if you're using the default spree storefront, please run the following generator:
+Now run the new authentication generator to connect your `Spree::User` model to Spree:
- ```bash
- bin/rails g spree:storefront:devise
- ```
+```bash
+bin/rails g spree:authentication:devise
+```
- This will add devise routes and create controllers for the storefront.
+And if you're using the default spree storefront, please run the following generator:
- And that's it! You can now login to the admin panel and storefront using your existing users.
- </Accordion>
- <Accordion title="5. Migrate data to the new format">
- In Spree 5 we changed a bit of the data in some models so you will need to run these commands to fix it:
+```bash
+bin/rails g spree:storefront:devise
+```
- #### Taxons
+This will add devise routes and create controllers for the storefront.
- ```ruby
- Spree::Taxon.all.each { |t| t.set_pretty_name; t.save }
- ```
- </Accordion>
-</AccordionGroup>
+And that's it! You can now login to the admin panel and storefront using your existing users.
+
+### 6. Migrate data to the new format
+
+In Spree 5 we changed a bit of the data in some models so you will need to run these commands to fix it:
+
+#### Taxons
+
+```ruby
+Spree::Taxon.all.each { |t| t.set_pretty_name; t.save }
+```
## Read the release notes
diff --git a/docs/developer/upgrades/4.6-to-4.7.mdx b/docs/developer/upgrades/4.6-to-4.7.mdx
index 1402f59006..7472418768 100644
--- a/docs/developer/upgrades/4.6-to-4.7.mdx
+++ b/docs/developer/upgrades/4.6-to-4.7.mdx
@@ -16,31 +16,27 @@ If you're on an older version than 4.6 please follow previous upgrade guides and
3. [upgrade 4.5 to 4.6](4.5-to-4.6)
</Note>
-<AccordionGroup>
- <Accordion title="1. Update gems">
+## Upgrade steps
- ```bash
- bundle update
- ```
- </Accordion>
+### 1. Update gems
- <Accordion title="2. Install and run missing migrations">
+```bash
+bundle update
+```
- ```bash
- bin/rake spree:install:migrations && bin/rails db:migrate
- ```
- </Accordion>
+### 2. Install and run missing migrations
- <Accordion title="3. (Optional) Re-Run Spree Frontend install">
+```bash
+bin/rake spree:install:migrations && bin/rails db:migrate
+```
- If you're using [Spree Frontend gem](https://github.com/spree/spree_rails_frontend), run the following additional commands to get everything set up correctly with the updated gems:
+### 3. (Optional) Re-Run Spree Frontend install
- ```bash
- bin/rails g spree:frontend:install
- ```
+If you're using [Spree Frontend gem](https://github.com/spree/spree_rails_frontend), run the following additional commands to get everything set up correctly with the updated gems:
- </Accordion>
-</AccordionGroup>
+```bash
+bin/rails g spree:frontend:install
+```
## Read the release notes
diff --git a/docs/developer/upgrades/4.8-to-4.9.mdx b/docs/developer/upgrades/4.8-to-4.9.mdx
index b101221168..608e7874f6 100644
--- a/docs/developer/upgrades/4.8-to-4.9.mdx
+++ b/docs/developer/upgrades/4.8-to-4.9.mdx
@@ -7,21 +7,19 @@ description: This guide covers upgrading a Spree 4.8 application to Spree 4.9.
Before proceeding to upgrade, please ensure you're at [Spree 4.8](/developer/upgrades/4.x-to-4.8)
</Info>
-<AccordionGroup>
- <Accordion title="1. Update gems">
+## Upgrade steps
- ```bash
- bundle update
- ```
- </Accordion>
+### 1. Update gems
- <Accordion title="2. Install and run missing migrations">
+```bash
+bundle update
+```
- ```bash
- bin/rake spree:install:migrations && bin/rails db:migrate
- ```
- </Accordion>
-</AccordionGroup>
+### 2. Install and run missing migrations
+
+```bash
+bin/rake spree:install:migrations && bin/rails db:migrate
+```
## Read the release notes
diff --git a/docs/developer/upgrades/4.9-to-4.10.mdx b/docs/developer/upgrades/4.9-to-4.10.mdx
index 8b2b78abd0..ffe6ecde1d 100644
--- a/docs/developer/upgrades/4.9-to-4.10.mdx
+++ b/docs/developer/upgrades/4.9-to-4.10.mdx
@@ -7,21 +7,19 @@ description: This guide covers upgrading a Spree 4.9 application to Spree 4.10.
Before proceeding to upgrade, please ensure you're at [Spree 4.9](/developer/upgrades/4.8-to-4.9)
</Info>
-<AccordionGroup>
- <Accordion title="1. Update gems">
+## Upgrade steps
- ```bash
- bundle update
- ```
- </Accordion>
+### 1. Update gems
- <Accordion title="2. Install and run missing migrations">
+```bash
+bundle update
+```
- ```bash
- bin/rake spree:install:migrations && bin/rails db:migrate
- ```
- </Accordion>
-</AccordionGroup>
+### 2. Install and run missing migrations
+
+```bash
+bin/rake spree:install:migrations && bin/rails db:migrate
+```
## Read the release notes
diff --git a/docs/developer/upgrades/4.x-to-4.8.mdx b/docs/developer/upgrades/4.x-to-4.8.mdx
index 294c06b5e6..0c31f5e37c 100644
--- a/docs/developer/upgrades/4.x-to-4.8.mdx
+++ b/docs/developer/upgrades/4.x-to-4.8.mdx
@@ -7,49 +7,47 @@ description: This guide covers upgrading a Spree 4 application to Spree 4.8.
Before proceeding to upgrade, please ensure you're at Spree 4.4 or later and Rails 6.1 or later.
</Info>
-<AccordionGroup>
- <Accordion title="1. Update gems">
+## Upgrade steps
- ```bash
- bundle update
- ```
- </Accordion>
+### 1. Update gems
- <Accordion title="2. Install and run missing migrations">
+```bash
+bundle update
+```
- ```bash
- bin/rake spree:install:migrations && bin/rails db:migrate
- ```
- </Accordion>
+### 2. Install and run missing migrations
- <Accordion title="3. (Optional) Install importmap-rails gem">
- We've switched to using [importmap-rails](https://github.com/rails/importmap-rails) for asset management. If you're using the `spree_backend` or `spree_frontend` gem, you'll need to install the `importmap-rails` gem.
+```bash
+bin/rake spree:install:migrations && bin/rails db:migrate
+```
- ```bash
- bundle add importmap-rails
- ```
+### 3. (Optional) Install importmap-rails gem
- and run generators:
+We've switched to using [importmap-rails](https://github.com/rails/importmap-rails) for asset management. If you're using the `spree_backend` or `spree_frontend` gem, you'll need to install the `importmap-rails` gem.
- ```bash
- bin/rails importmap:install && bin/rails turbo:install && bin/rails stimulus:install
- ```
+```bash
+bundle add importmap-rails
+```
- You can also remove the `jsbundling-rails` gem from your `Gemfile`:
+and run generators:
- ```bash
- bundle remove jsbundling-rails
- ```
- </Accordion>
+```bash
+bin/rails importmap:install && bin/rails turbo:install && bin/rails stimulus:install
+```
- <Accordion title="4. (Optional) Apply fix when upgrading from 4.5/4.6/4.7">
- If you're upgrading from 4.5/4.6/4.7, you need to set this configuration in your `config/initializers/spree.rb`:
+You can also remove the `jsbundling-rails` gem from your `Gemfile`:
- ```ruby
- Spree::RuntimeConfig.always_use_translations = true
- ```
- </Accordion>
-</AccordionGroup>
+```bash
+bundle remove jsbundling-rails
+```
+
+### 4. (Optional) Apply fix when upgrading from 4.5/4.6/4.7
+
+If you're upgrading from 4.5/4.6/4.7, you need to set this configuration in your `config/initializers/spree.rb`:
+
+```ruby
+Spree::RuntimeConfig.always_use_translations = true
+```
## Read the release notes
diff --git a/docs/developer/upgrades/5.0-to-5.1.mdx b/docs/developer/upgrades/5.0-to-5.1.mdx
index aa79d5cedc..8db03a8838 100644
--- a/docs/developer/upgrades/5.0-to-5.1.mdx
+++ b/docs/developer/upgrades/5.0-to-5.1.mdx
@@ -9,26 +9,22 @@ description: This guide covers upgrading a Spree 5.0 application to Spree 5.1.
## Upgrade steps
-<AccordionGroup>
- <Accordion title="1. Update gems">
+### 1. Update gems
- ```bash
- bundle update
- ```
- </Accordion>
+```bash
+bundle update
+```
- <Accordion title="2. Install and run missing migrations">
+### 2. Install and run missing migrations
- ```bash
- bin/rake spree:install:migrations && bin/rails db:migrate
- ```
- </Accordion>
+```bash
+bin/rake spree:install:migrations && bin/rails db:migrate
+```
- <Accordion title="3. Migrate admin user accounts to the new system">
- Spree 5.1 introduces a new better way of managing admin user accounts. To ensure your existing admin user accounts are migrated to the new system, run the following command:
+### 3. Migrate admin user accounts to the new system
- ```bash
- bin/rake db:migrate_admin_users_to_role_users
- ```
- </Accordion>
-</AccordionGroup>
+Spree 5.1 introduces a new better way of managing admin user accounts. To ensure your existing admin user accounts are migrated to the new system, run the following command:
+
+```bash
+bin/rake db:migrate_admin_users_to_role_users
+```
diff --git a/docs/developer/upgrades/5.2-to-5.3.mdx b/docs/developer/upgrades/5.2-to-5.3.mdx
new file mode 100644
index 0000000000..8dad301b2e
--- /dev/null
+++ b/docs/developer/upgrades/5.2-to-5.3.mdx
@@ -0,0 +1,81 @@
+---
+title: Upgrading to Spree 5.3
+description: This guide covers upgrading a Spree 5.2 application to Spree 5.3.
+---
+
+<Info>
+ Before proceeding to upgrade, please ensure you're at [Spree 5.2](/developer/upgrades/5.1-to-5.2)
+</Info>
+
+## Upgrade steps
+
+### Update gems
+
+ ```bash
+ bundle update
+ ```
+
+### Fetch and run missing migrations
+
+```bash
+bin/rake spree:install:migrations && bin/rails db:migrate
+```
+
+This will setup new database schema for the new features in Spree 5.3 like Price Lists and Customer Groups.
+
+### Run counter cache rake tasks
+
+Spree 5.3 introduces counter caches for products, taxons and variants. You need to run the following rake tasks to populate the counter caches:
+
+ ```bash
+ bin/rake spree:products:reset_counter_caches
+ bin/rake spree:taxons:reset_counter_caches
+ bin/rake spree:variants:reset_counter_caches
+ ```
+
+This will greatly improve the performance of your application by avoiding N+1 queries.
+
+<Warning>
+ You will need to run this rake task locally and on your production environment to ensure that the counter caches are populated correctly.
+</Warning>
+
+### Generate product metrics
+
+Spree 5.3 introduces product metrics for products. You need to run the following rake task to populate the product metrics:
+
+ ```bash
+ bin/rake spree:products:populate_metrics
+ ```
+
+This will populate the product metrics for all products in your database. Product metrics are used to sort products by best selling scope.
+
+<Warning>
+ You will need to run this rake task locally and on your production environment to ensure that the product metrics are populated correctly.
+</Warning>
+
+This rake task will enqueue background jobs to populate the product metrics for all products in your database so you need to make sure that your background jobs are configured correctly.
+
+### Re-run Admin Panel Install Generator
+
+Admin Panel was completely rewritten to use Tailwind v4 so you need to re-run the install generator to setup Tailwind and remove any Dart Sass related files.
+
+ ```bash
+ bin/rails g spree:admin:install
+ ```
+
+This will also modify your `Procfile.dev` file to include the new Tailwind CSS watch task instead of the old Dart Sass watch task.
+
+### Update Storefront to Tailwind v4
+
+Spree 5.3 requires Tailwind v4 as it's also used now for the Admin panel so you need to update your Storefront to Tailwind v4 as well.
+
+Running `bundle update` previously installed Tailwind v4. You only need to run
+
+ ```bash
+ bin/rails g spree:storefront:install
+ ```
+
+This will:
+
+1. Overwrite `config/tailwind.config.js` file with the new Tailwind v4 configuration.
+2. Add `app/assets/tailwind/application.css` file with the new Tailwind v4 styles. If you modified `app/assets/stylesheets/application.tailwind.css` file, you will need to merge your changes with the new one.
diff --git a/docs/docs.json b/docs/docs.json
index c78a3719e2..c6cc74fda3 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -43,6 +43,14 @@
{
"source": "/developer/customization/webhooks",
"destination": "/developer/core-concepts/webhooks"
+ },
+ {
+ "source": "/developer/customization/promotions",
+ "destination": "/developer/core-concepts/promotions"
+ },
+ {
+ "source": "/developer/extending-spree/promotions",
+ "destination": "/developer/core-concepts/promotions"
}
],
"contextual": {
@@ -216,6 +224,7 @@
{
"group": "Upgrade Guides",
"pages": [
+ "developer/upgrades/5.2-to-5.3",
"developer/upgrades/5.1-to-5.2",
"developer/upgrades/5.0-to-5.1",
"developer/upgrades/4.10-to-5.0",