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] Document Reports, Imports, Exports + guide how to create custom reports

Damian Legawiecab744b36b987
diff --git a/docs/developer/core-concepts/imports-exports.mdx b/docs/developer/core-concepts/imports-exports.mdx
new file mode 100644
index 0000000000..ce286c464f
--- /dev/null
+++ b/docs/developer/core-concepts/imports-exports.mdx
@@ -0,0 +1,698 @@
+---
+title: Imports & Exports
+---
+
+## Overview
+
+Spree provides a comprehensive bulk data import and export system for managing large datasets. The system supports CSV file processing with configurable field mapping, asynchronous processing via background jobs, and real-time progress tracking in the admin interface.
+
+### Import/Export System Diagram
+
+```mermaid
+erDiagram
+ Import {
+ string number
+ string type
+ string status
+ bigint owner_id
+ string owner_type
+ bigint user_id
+ }
+
+ ImportMapping {
+ string schema_field
+ string file_column
+ }
+
+ ImportRow {
+ integer row_number
+ text data
+ string status
+ text validation_errors
+ }
+
+ ImportSchema {
+ array fields
+ }
+
+ RowProcessor {
+ hash attributes
+ }
+
+ Export {
+ string number
+ string type
+ string format
+ jsonb search_params
+ }
+
+ Store {
+ string name
+ }
+
+ Import ||--|| Store : "belongs to (owner)"
+ Import ||--o{ ImportMapping : "has many"
+ Import ||--o{ ImportRow : "has many"
+ Import ||--|| ImportSchema : "uses"
+ ImportRow ||--|| RowProcessor : "processed by"
+ Export ||--|| Store : "belongs to"
+```
+
+## Architecture
+
+The import/export system uses several design patterns:
+
+1. **Single Table Inheritance (STI)**: Import and Export types inherit from base classes
+2. **State Machine**: Imports progress through states (pending → mapping → processing → completed)
+3. **Schema Definition**: ImportSchema classes define expected fields and validation
+4. **Row Processors**: Transform CSV rows into database records
+5. **Event-Driven Processing**: Background jobs handle heavy lifting asynchronously
+6. **Registry Pattern**: Types registered in `Spree.import_types` and `Spree.export_types`
+
+---
+
+## Exports
+
+Exports generate CSV files from filtered database records.
+
+### Built-in Export Types
+
+| Type | Description | Multi-line |
+|------|-------------|------------|
+| `Spree::Exports::Products` | Products with all variants | Yes |
+| `Spree::Exports::Orders` | Orders with line items | Yes |
+| `Spree::Exports::Customers` | Customer accounts | No |
+| `Spree::Exports::GiftCards` | Gift cards | No |
+| `Spree::Exports::NewsletterSubscribers` | Newsletter subscribers | No |
+
+### Export Model
+
+The base `Spree::Export` class provides:
+
+```ruby
+module Spree
+ class Export < Spree.base_class
+ # Associations
+ belongs_to :store
+ belongs_to :user # Admin who created export
+
+ # Attachments
+ has_one_attached :attachment # Generated CSV file
+
+ # Key methods
+ def csv_headers # Define column headers
+ def scope # Base query with store/vendor filtering
+ def scope_includes # Eager loading associations
+ def records_to_export # Apply ransack filters
+ def multi_line_csv? # True if records produce multiple rows
+ def generate # Create CSV and attach file
+ end
+end
+```
+
+### Creating a Custom Exporter
+
+**Step 1: Create the Export Class**
+
+```ruby app/models/spree/exports/subscriptions.rb
+module Spree
+ module Exports
+ class Subscriptions < Spree::Export
+ # Define CSV column headers
+ def csv_headers
+ %w[id email plan_name status created_at] + metafields_headers
+ end
+
+ # Eager load associations to avoid N+1 queries
+ def scope_includes
+ [:user, :plan, { metafields: :metafield_definition }]
+ end
+
+ # Override scope if needed (e.g., exclude cancelled)
+ def scope
+ super.where.not(status: 'cancelled')
+ end
+
+ # Set to true if each record produces multiple CSV rows
+ def multi_line_csv?
+ false
+ end
+ end
+ end
+end
+```
+
+**Step 2: Add `to_csv` Method to Your Model**
+
+```ruby app/models/spree/subscription.rb
+module Spree
+ class Subscription < Spree.base_class
+ def to_csv(store)
+ [
+ id,
+ user&.email,
+ plan&.name,
+ status,
+ created_at.iso8601
+ ] + metafields_csv_values(store)
+ end
+
+ private
+
+ def metafields_csv_values(store)
+ Spree::MetafieldDefinition.for_resource_type(self.class.name).order(:namespace, :key).map do |definition|
+ metafields.find { |m| m.metafield_definition_id == definition.id }&.value
+ end
+ end
+ end
+end
+```
+
+**Step 3: Register the Export Type**
+
+```ruby config/initializers/spree.rb
+Rails.application.config.after_initialize do
+ Spree.export_types << Spree::Exports::Subscriptions
+end
+```
+
+**Step 4: Add Translations**
+
+```yaml config/locales/en.yml
+en:
+ spree:
+ subscriptions: Subscriptions
+```
+
+### Multi-line Exports
+
+For exports where each record produces multiple rows (like products with variants):
+
+```ruby app/models/spree/exports/orders_with_items.rb
+module Spree
+ module Exports
+ class OrdersWithItems < Spree::Export
+ def multi_line_csv?
+ true
+ end
+
+ def csv_headers
+ %w[order_number line_item_sku quantity price]
+ end
+
+ def scope_includes
+ [line_items: :variant]
+ end
+ end
+ end
+end
+```
+
+```ruby app/models/spree/order.rb
+# In the Order model
+def to_csv(store)
+ line_items.map do |item|
+ [number, item.variant.sku, item.quantity, item.price]
+ end
+end
+```
+
+### Export Filtering
+
+Exports support Ransack filtering via `search_params`:
+
+```ruby
+# In admin, users can filter before exporting
+export = Spree::Exports::Products.new(
+ store: current_store,
+ user: current_user,
+ search_params: { name_cont: 'shirt', status_eq: 'active' }.to_json,
+ record_selection: 'filtered' # or 'all' to ignore filters
+)
+```
+
+---
+
+## Imports
+
+Imports process CSV files to create or update database records.
+
+### Built-in Import Types
+
+| Type | Description |
+|------|-------------|
+| `Spree::Imports::Products` | Products and variants |
+
+### Import Workflow
+
+```
+1. Upload CSV → pending
+2. Auto-map columns → mapping
+3. User confirms mapping → completed_mapping
+4. Parse rows (CreateRowsJob) → processing
+5. Process rows (ProcessRowsJob) → completed/failed
+```
+
+### Import Components
+
+#### Import Model
+
+```ruby
+module Spree
+ class Import < Spree.base_class
+ # Associations
+ belongs_to :owner, polymorphic: true # Store or Vendor
+ belongs_to :user
+ has_many :mappings # Field mappings
+ has_many :rows # CSV rows to process
+
+ # State machine
+ state_machine initial: :pending do
+ event :start_mapping do
+ transition to: :mapping
+ end
+ event :complete_mapping do
+ transition from: :mapping, to: :completed_mapping
+ end
+ event :start_processing do
+ transition from: :completed_mapping, to: :processing
+ end
+ event :complete do
+ transition from: :processing, to: :completed
+ end
+ event :fail do
+ transition to: :failed
+ end
+ end
+
+ # Key methods
+ def import_schema # Returns schema class instance
+ def row_processor_class # Returns processor class
+ def schema_fields # Fields from schema + metafields
+ def mapping_done? # All required fields mapped?
+ end
+end
+```
+
+#### Import Schema
+
+Defines expected CSV fields:
+
+```ruby
+module Spree
+ class ImportSchema
+ FIELDS = []
+
+ def fields
+ self.class::FIELDS
+ end
+
+ def required_fields
+ FIELDS.select { |f| f[:required] }.map { |f| f[:name] }
+ end
+
+ def optional_fields
+ FIELDS.reject { |f| f[:required] }.map { |f| f[:name] }
+ end
+ end
+end
+```
+
+#### Import Mapping
+
+Maps CSV columns to schema fields:
+
+```ruby
+module Spree
+ class ImportMapping < Spree.base_class
+ belongs_to :import
+
+ # Attributes
+ # schema_field - target field name from schema
+ # file_column - CSV column header
+
+ def try_to_auto_assign_file_column(csv_headers)
+ # Matches by parameterized name comparison
+ self.file_column = csv_headers.find do |header|
+ header.parameterize.underscore == schema_field.parameterize.underscore
+ end
+ end
+ end
+end
+```
+
+#### Import Row
+
+Represents a single CSV row:
+
+```ruby
+module Spree
+ class ImportRow < Spree.base_class
+ belongs_to :import, counter_cache: :rows_count
+ belongs_to :item, polymorphic: true, optional: true # Created record
+
+ # Attributes
+ # row_number - position in CSV
+ # data - JSON-serialized row data
+ # status - pending/processing/completed/failed
+ # validation_errors - error message if failed
+
+ def process!
+ start_processing!
+ self.item = import.row_processor_class.new(self).process!
+ complete!
+ rescue StandardError => e
+ self.validation_errors = e.message
+ fail!
+ end
+
+ def to_schema_hash
+ # Maps CSV data using import.mappings
+ end
+ end
+end
+```
+
+#### Row Processor
+
+Transforms row data into database records:
+
+```ruby
+module Spree
+ module Imports
+ module RowProcessors
+ class Base
+ def initialize(row)
+ @row = row
+ @import = row.import
+ @attributes = row.to_schema_hash
+ end
+
+ attr_reader :row, :import, :attributes
+
+ def process!
+ raise NotImplementedError
+ end
+ end
+ end
+ end
+end
+```
+
+### Creating a Custom Importer
+
+**Step 1: Create the Import Class**
+
+```ruby app/models/spree/imports/subscriptions.rb
+module Spree
+ module Imports
+ class Subscriptions < Spree::Import
+ def row_processor_class
+ Spree::Imports::RowProcessors::Subscription
+ end
+ end
+ end
+end
+```
+
+**Step 2: Define the Schema**
+
+```ruby app/models/spree/import_schemas/subscriptions.rb
+module Spree
+ module ImportSchemas
+ class Subscriptions < Spree::ImportSchema
+ FIELDS = [
+ { name: 'email', label: 'Customer Email', required: true },
+ { name: 'plan_name', label: 'Plan Name', required: true },
+ { name: 'status', label: 'Status', required: true },
+ { name: 'start_date', label: 'Start Date' },
+ { name: 'billing_interval', label: 'Billing Interval' },
+ { name: 'amount', label: 'Amount' },
+ { name: 'currency', label: 'Currency' }
+ ].freeze
+ end
+ end
+end
+```
+
+**Step 3: Create the Row Processor**
+
+```ruby app/services/spree/imports/row_processors/subscription.rb
+module Spree
+ module Imports
+ module RowProcessors
+ class Subscription < Base
+ def process!
+ user = find_or_create_user
+ plan = find_plan
+
+ subscription = Spree::Subscription.find_or_initialize_by(
+ user: user,
+ plan: plan
+ )
+
+ subscription.status = attributes['status'] if attributes['status'].present?
+ subscription.start_date = parse_date(attributes['start_date']) if attributes['start_date'].present?
+ subscription.billing_interval = attributes['billing_interval'] if attributes['billing_interval'].present?
+
+ if attributes['amount'].present?
+ currency = attributes['currency'].presence || import.store.default_currency
+ subscription.set_price(currency, attributes['amount'])
+ end
+
+ subscription.save!
+ subscription
+ end
+
+ private
+
+ def find_or_create_user
+ email = attributes['email'].strip.downcase
+ Spree.user_class.find_or_create_by!(email: email)
+ end
+
+ def find_plan
+ Spree::Plan.find_by!(name: attributes['plan_name'].strip)
+ end
+
+ def parse_date(date_string)
+ Date.parse(date_string)
+ rescue ArgumentError
+ nil
+ end
+ end
+ end
+ end
+end
+```
+
+**Step 4: Register the Import Type**
+
+```ruby config/initializers/spree.rb
+Rails.application.config.after_initialize do
+ Spree.import_types << Spree::Imports::Subscriptions
+end
+```
+
+**Step 5: Add Translations**
+
+```yaml config/locales/en.yml
+en:
+ spree:
+ subscriptions: Subscriptions
+```
+
+### Products Import Schema
+
+The built-in products import supports these fields:
+
+**Required Fields:**
+- `slug` - Product URL slug
+- `sku` - Variant SKU
+- `name` - Product name
+- `price` - Variant price
+
+**Optional Fields:**
+- `status` - Product status (active/draft/archived)
+- `description` - Product description
+- `meta_title`, `meta_description`, `meta_keywords` - SEO metadata
+- `tags` - Product tags
+- `compare_at_price` - Original price for sale display
+- `currency` - Price currency
+- `width`, `height`, `depth`, `dimensions_unit` - Dimensions
+- `weight`, `weight_unit` - Weight
+- `available_on`, `discontinue_on` - Availability dates
+- `track_inventory` - Enable inventory tracking
+- `inventory_count`, `inventory_backorderable` - Stock settings
+- `tax_category`, `shipping_category` - Category assignments
+- `image1_src`, `image2_src`, `image3_src` - Image URLs
+- `option1_name`, `option1_value` through `option3_name`, `option3_value` - Variant options
+- `category1`, `category2`, `category3` - Taxon assignments (format: "Taxonomy -> Taxon -> Child Taxon")
+
+### Handling Multi-Variant Products
+
+The products import handles variants intelligently:
+
+1. **Master variant rows** (no option values): Create/update the product and its master variant
+2. **Non-master variant rows** (with option values): Create additional variants for an existing product
+
+```csv
+slug,sku,name,price,option1_name,option1_value,option2_name,option2_value
+my-tshirt,TSHIRT-001,My T-Shirt,29.99,,,
+my-tshirt,TSHIRT-S-RED,My T-Shirt,29.99,Size,Small,Color,Red
+my-tshirt,TSHIRT-M-RED,My T-Shirt,29.99,Size,Medium,Color,Red
+my-tshirt,TSHIRT-L-RED,My T-Shirt,29.99,Size,Large,Color,Red
+```
+
+### Metafield Support
+
+Both imports and exports support metafields dynamically:
+
+**Export:** Metafield definitions are automatically added as CSV columns using the format `metafield.{namespace}.{key}`.
+
+**Import:** Map CSV columns to metafield definitions. The system automatically detects columns matching the metafield pattern and updates the corresponding metafield values.
+
+---
+
+## Background Jobs
+
+### CreateRowsJob
+
+Parses CSV and creates ImportRow records:
+
+```ruby
+module Spree
+ module Imports
+ class CreateRowsJob < Spree::BaseJob
+ queue_as Spree.queues.imports
+
+ def perform(import_id)
+ import = Spree::Import.find(import_id)
+ # Stream CSV, batch insert rows
+ # Then enqueue ProcessRowsJob
+ end
+ end
+ end
+end
+```
+
+### ProcessRowsJob
+
+Processes pending rows through row processors:
+
+```ruby
+module Spree
+ module Imports
+ class ProcessRowsJob < Spree::BaseJob
+ queue_as Spree.queues.imports
+
+ def perform(import_id)
+ import = Spree::Import.find(import_id)
+ import.rows.pending_and_failed.find_each do |row|
+ row.process!
+ end
+ import.complete!
+ end
+ end
+ end
+end
+```
+
+### GenerateJob (Exports)
+
+Generates CSV files for exports:
+
+```ruby
+module Spree
+ module Exports
+ class GenerateJob < Spree::BaseJob
+ queue_as Spree.queues.exports
+
+ def perform(export_id)
+ export = Spree::Export.find(export_id)
+ export.generate
+ end
+ end
+ end
+end
+```
+
+---
+
+## Events
+
+### Import Events
+
+| Event | Trigger |
+|-------|---------|
+| `import.created` | Import record created |
+| `import.completed` | All rows processed |
+
+### Export Events
+
+| Event | Trigger |
+|-------|---------|
+| `export.created` | Export record created (triggers generation) |
+
+### Import Row Events
+
+| Event | Trigger |
+|-------|---------|
+| `import_row.completed` | Row processed successfully |
+| `import_row.failed` | Row processing failed |
+
+---
+
+## Configuration
+
+### Queue Configuration
+
+```ruby config/initializers/spree.rb
+# Configure job queues
+Spree.queues.imports = :imports
+Spree.queues.exports = :exports
+```
+
+### Preferences
+
+Imports support configurable delimiter:
+
+```ruby
+import.preferred_delimiter = ';' # Default: ','
+```
+
+---
+
+## Key Files Reference
+
+| File | Purpose |
+|------|---------|
+| `core/app/models/spree/import.rb` | Base import model |
+| `core/app/models/spree/export.rb` | Base export model |
+| `core/app/models/spree/import_schema.rb` | Base schema class |
+| `core/app/models/spree/import_mapping.rb` | Field mapping model |
+| `core/app/models/spree/import_row.rb` | Row model with processing |
+| `core/app/models/spree/imports/products.rb` | Products import type |
+| `core/app/models/spree/import_schemas/products.rb` | Products schema |
+| `core/app/services/spree/imports/row_processors/base.rb` | Base processor |
+| `core/app/services/spree/imports/row_processors/product_variant.rb` | Products processor |
+| `core/app/models/spree/exports/products.rb` | Products export |
+| `core/app/models/spree/exports/orders.rb` | Orders export |
+| `core/app/models/spree/exports/customers.rb` | Customers export |
+| `core/app/jobs/spree/imports/create_rows_job.rb` | Row creation job |
+| `core/app/jobs/spree/imports/process_rows_job.rb` | Row processing job |
+| `core/app/jobs/spree/exports/generate_job.rb` | Export generation job |
+| `admin/app/controllers/spree/admin/imports_controller.rb` | Admin imports controller |
+| `admin/app/controllers/spree/admin/exports_controller.rb` | Admin exports controller |
+
+## Permissions
+
+Access is controlled via CanCanCan:
+
+```ruby
+# Allow admin to manage imports/exports
+can :manage, Spree::Import
+can :manage, Spree::Export
+```
+
+Records are filtered by `current_ability` ensuring users only export data they have access to.
diff --git a/docs/developer/core-concepts/reports.mdx b/docs/developer/core-concepts/reports.mdx
new file mode 100644
index 0000000000..a012902c3b
--- /dev/null
+++ b/docs/developer/core-concepts/reports.mdx
@@ -0,0 +1,696 @@
+---
+title: Reports
+---
+
+## Overview
+
+Spree provides a flexible reporting system that allows you to generate data exports for sales analytics, product performance, and custom business metrics. Reports are generated asynchronously and delivered as downloadable CSV files.
+
+### Report System Diagram
+
+```mermaid
+erDiagram
+ Report {
+ string type
+ string currency
+ datetime date_from
+ datetime date_to
+ bigint store_id
+ bigint user_id
+ }
+
+ ReportLineItem {
+ string record
+ string report
+ }
+
+ Store {
+ string name
+ string code
+ }
+
+ AdminUser {
+ string email
+ }
+
+ GenerateJob {
+ string report_id
+ }
+
+ Report ||--|| Store : "belongs to"
+ Report ||--o| AdminUser : "belongs to"
+ Report ||--o{ ReportLineItem : "generates"
+ Report ||--|| GenerateJob : "triggers"
+```
+
+**Key relationships:**
+- **Report** is the base model for all report types using Single Table Inheritance (STI)
+- **ReportLineItem** transforms raw database records into formatted report rows
+- Reports are scoped to a **Store** and optionally track the **AdminUser** who created them
+- **GenerateJob** handles asynchronous CSV generation via the events system
+
+## Architecture
+
+The reporting system uses several design patterns:
+
+1. **Single Table Inheritance (STI)**: All report types inherit from `Spree::Report` and are stored in the same database table with a `type` column
+2. **Presenter Pattern**: `Spree::ReportLineItem` subclasses transform raw records into formatted output
+3. **Event-Driven Processing**: Report generation is triggered asynchronously via Spree's events system
+4. **Registry Pattern**: Reports are registered in `Spree.reports` for discovery and validation
+
+## Built-in Reports
+
+Spree ships with two built-in reports:
+
+### Sales Total Report
+
+The Sales Total report provides line-item level detail for all completed orders within a date range.
+
+**Columns:**
+- `date` - Order completion date
+- `order` - Order number
+- `product` - Variant descriptive name
+- `quantity` - Line item quantity
+- `pre_tax_amount` - Amount before taxes
+- `promo_total` - Promotion discounts applied
+- `shipment_total` - Shipping costs
+- `tax_total` - Tax amount
+- `total` - Final amount including all adjustments
+
+### Products Performance Report
+
+The Products Performance report aggregates sales metrics by product for the specified period.
+
+**Columns:**
+- `sku` - Product SKU
+- `name` - Product name
+- `vendor` - Vendor name (if multi-vendor enabled)
+- `brand` - Brand name
+- `category_lvl0/1/2` - Category hierarchy from main taxon
+- `price` - Current product price
+- `weeks_online` - Weeks since product became available
+- `pre_tax_amount` - Total pre-tax sales
+- `tax_total` - Total taxes collected
+- `quantity` - Total units sold
+- `promo_total` - Total promotion discounts
+- `total` - Total revenue
+
+## Creating Custom Reports
+
+To create a custom report, you need three components:
+
+1. A report class that defines the data query
+2. A line item class that formats each row
+3. Registration in `Spree.reports`
+
+### Step 1: Create the Report Class
+
+Create a new report class that inherits from `Spree::Report`:
+
+```ruby app/models/spree/reports/customer_orders.rb
+module Spree
+ module Reports
+ class CustomerOrders < Spree::Report
+ # Define the scope of records to include in the report
+ def line_items_scope
+ store.orders.complete.where(
+ completed_at: date_from..date_to,
+ currency: currency
+ ).includes(:user, :bill_address)
+ end
+ end
+ end
+end
+```
+
+The `line_items_scope` method must return an `ActiveRecord::Relation` that defines what records appear in the report. This method has access to:
+
+- `store` - The current store
+- `date_from` - Report start date
+- `date_to` - Report end date
+- `currency` - Report currency
+- `vendor` - Vendor (if multi-vendor is enabled)
+
+### Step 2: Create the Line Item Class
+
+Create a corresponding line item class that transforms each record into report columns:
+
+```ruby app/models/spree/report_line_items/customer_orders.rb
+module Spree
+ module ReportLineItems
+ class CustomerOrders < Spree::ReportLineItem
+ # Define attributes that will become columns
+ attribute :order_number, :string
+ attribute :completed_at, :string
+ attribute :customer_email, :string
+ attribute :customer_name, :string
+ attribute :item_count, :integer
+ attribute :total, :string
+
+ # Map record fields to report columns
+ def order_number
+ record.number
+ end
+
+ def completed_at
+ record.completed_at.strftime('%Y-%m-%d %H:%M')
+ end
+
+ def customer_email
+ record.email
+ end
+
+ def customer_name
+ record.bill_address&.full_name
+ end
+
+ def item_count
+ record.line_items.sum(:quantity)
+ end
+
+ def total
+ Spree::Money.new(record.total, currency: currency)
+ end
+ end
+ end
+end
+```
+
+**Important notes:**
+- The class name must match the report class name (e.g., `Reports::CustomerOrders` -> `ReportLineItems::CustomerOrders`)
+- Use `attribute` to define columns with their types
+- Each attribute needs a corresponding method that extracts/formats data from `record`
+- `record` is a single item from `line_items_scope`
+- Use `Spree::Money` for currency formatting
+- `currency` and `store` are delegated from the report
+
+### Step 3: Register the Report
+
+Add your report to the registry in an initializer:
+
+```ruby config/initializers/spree.rb
+Rails.application.config.after_initialize do
+ Spree.reports << Spree::Reports::CustomerOrders
+end
+```
+
+### Step 4: Add Translations
+
+Add the report name translation:
+
+```yaml config/locales/en.yml
+en:
+ spree:
+ report_names:
+ customer_orders: Customer Orders
+```
+
+Also add translations for any custom column headers:
+
+```yaml config/locales/en.yml
+en:
+ spree:
+ order_number: Order Number
+ completed_at: Completed At
+ customer_email: Customer Email
+ customer_name: Customer Name
+ item_count: Item Count
+ total: Total
+```
+
+## Advanced Customization
+
+### Complex Queries with Aggregations
+
+For reports that aggregate data, you can use SQL directly:
+
+```ruby app/models/spree/reports/revenue_by_category.rb
+module Spree
+ module Reports
+ class RevenueByCategory < Spree::Report
+ def line_items_scope
+ line_items_sql = Spree::LineItem
+ .joins(:order)
+ .where(
+ spree_orders: {
+ completed_at: date_from..date_to,
+ currency: currency
+ }
+ )
+ .select(
+ "spree_line_items.variant_id",
+ "SUM(spree_line_items.quantity) as quantity",
+ "SUM(spree_line_items.pre_tax_amount) as revenue"
+ )
+ .group(:variant_id)
+ .to_sql
+
+ store.taxons
+ .where(depth: 1) # Top-level categories
+ .joins("LEFT JOIN spree_products_taxons ON spree_products_taxons.taxon_id = spree_taxons.id")
+ .joins("LEFT JOIN spree_variants ON spree_variants.product_id = spree_products_taxons.product_id")
+ .joins("LEFT JOIN (#{line_items_sql}) AS line_items ON line_items.variant_id = spree_variants.id")
+ .select(
+ "spree_taxons.*",
+ "COALESCE(SUM(line_items.quantity), 0) AS total_quantity",
+ "COALESCE(SUM(line_items.revenue), 0.0) AS total_revenue"
+ )
+ .group("spree_taxons.id")
+ end
+ end
+ end
+end
+```
+
+### Custom Summary Section
+
+Override `to_partial_path` to use a custom template with a summary:
+
+```ruby app/models/spree/reports/customer_orders.rb
+module Spree
+ module Reports
+ class CustomerOrders < Spree::Report
+ def summary
+ {
+ total_orders: line_items_scope.count,
+ total_revenue: line_items_scope.sum(:total),
+ average_order_value: line_items_scope.average(:total)
+ }
+ end
+ end
+ end
+end
+```
+
+### Multi-Vendor Support
+
+If you're using Spree Multi-Vendor, filter by vendor:
+
+```ruby app/models/spree/reports/vendor_sales.rb
+module Spree
+ module Reports
+ class VendorSales < Spree::Report
+ def line_items_scope
+ scope = store.line_items.where(
+ order: Spree::Order.complete.where(
+ completed_at: date_from..date_to,
+ currency: currency
+ )
+ )
+
+ # Filter by vendor if one is selected
+ scope = scope.where(vendor_id: vendor.id) if defined?(vendor) && vendor.present?
+
+ scope
+ end
+ end
+ end
+end
+```
+
+## How Reports Work Internally
+
+### Generation Flow
+
+1. **User creates report** via admin UI with date range, currency, and optional vendor
+2. **Report is saved** to database with status tracking
+3. **`report.created` event fires** via `publishes_lifecycle_events` concern
+4. **`Spree::ReportSubscriber` catches event** and enqueues `GenerateJob`
+5. **Background job runs `report.generate`**:
+ - Iterates through `line_items_scope` in batches
+ - Transforms each record via `ReportLineItem`
+ - Writes CSV to temp file
+ - Attaches CSV to report via ActiveStorage
+ - Sends notification email to user
+
+### Key Files
+
+| File | Purpose |
+|------|---------|
+| `core/app/models/spree/report.rb` | Base report model |
+| `core/app/models/spree/report_line_item.rb` | Base line item presenter |
+| `core/app/models/spree/reports/*.rb` | Built-in report implementations |
+| `core/app/models/spree/report_line_items/*.rb` | Built-in line item formatters |
+| `core/app/subscribers/spree/report_subscriber.rb` | Event subscriber for async generation |
+| `core/app/jobs/spree/reports/generate_job.rb` | Background job for CSV creation |
+| `core/app/mailers/spree/report_mailer.rb` | Notification emails |
+| `admin/app/controllers/spree/admin/reports_controller.rb` | Admin UI controller |
+
+### Report Base Class Methods
+
+```ruby
+# Returns the scope of records for the report
+def line_items_scope
+ raise NotImplementedError
+end
+
+# Returns formatted line items (with optional limit for preview)
+def line_items(options = {})
+ scope = line_items_scope
+ scope = scope.limit(options[:limit]) if options[:limit].present?
+ scope.map { |record| line_item_class.new(record: record, report: self) }
+end
+
+# Generates the CSV file and handles attachment
+def generate
+ generate_csv
+ handle_attachment
+ send_report_done_email
+end
+
+# Returns the corresponding line item class
+def line_item_class
+ "Spree::ReportLineItems::#{type.demodulize}".safe_constantize
+end
+```
+
+### ReportLineItem Base Class Methods
+
+```ruby
+# Returns column headers for display
+def self.headers
+ attribute_types.keys.map do |attribute|
+ { name: attribute.to_sym, label: Spree.t(attribute.to_sym) }
+ end
+end
+
+# Returns column names for CSV header row
+def self.csv_headers
+ attribute_types.keys
+end
+
+# Converts line item to CSV row array
+def to_csv
+ self.class.attribute_types.keys.map { |attr| send(attr) }
+end
+```
+
+## Testing Custom Reports
+
+Testing custom reports ensures they correctly query data and format output. Here's how to write comprehensive specs for your reports.
+
+### Testing the Report Class
+
+Test that your report's `line_items_scope` returns the correct records:
+
+```ruby spec/models/spree/reports/customer_orders_spec.rb
+require 'rails_helper'
+
+RSpec.describe Spree::Reports::CustomerOrders, type: :model do
+ let(:store) { create(:store) }
+ let(:user) { create(:admin_user) }
+
+ subject(:report) do
+ described_class.new(
+ store: store,
+ user: user,
+ currency: 'USD',
+ date_from: 1.month.ago,
+ date_to: Time.current
+ )
+ end
+
+ describe '#line_items_scope' do
+ let!(:completed_order) do
+ create(:completed_order_with_totals, store: store, currency: 'USD', completed_at: 1.week.ago)
+ end
+
+ let!(:incomplete_order) do
+ create(:order, store: store, currency: 'USD', state: 'cart')
+ end
+
+ let!(:other_currency_order) do
+ create(:completed_order_with_totals, store: store, currency: 'EUR', completed_at: 1.week.ago)
+ end
+
+ let!(:old_order) do
+ create(:completed_order_with_totals, store: store, currency: 'USD', completed_at: 2.months.ago)
+ end
+
+ it 'returns only completed orders within the date range and currency' do
+ scope = report.line_items_scope
+
+ expect(scope).to include(completed_order)
+ expect(scope).not_to include(incomplete_order)
+ expect(scope).not_to include(other_currency_order)
+ expect(scope).not_to include(old_order)
+ end
+ end
+
+ describe '#line_items' do
+ let!(:order) do
+ create(:completed_order_with_totals, store: store, currency: 'USD', completed_at: 1.week.ago)
+ end
+
+ it 'returns ReportLineItem objects' do
+ items = report.line_items
+ expect(items).to all(be_a(Spree::ReportLineItems::CustomerOrders))
+ end
+
+ it 'respects the limit option' do
+ create(:completed_order_with_totals, store: store, currency: 'USD', completed_at: 2.days.ago)
+ items = report.line_items(limit: 1)
+ expect(items.length).to eq(1)
+ end
+ end
+
+ describe 'registration' do
+ it 'is registered in Spree.reports' do
+ expect(Spree.reports).to include(described_class)
+ end
+ end
+
+ describe '#line_item_class' do
+ it 'resolves to the correct ReportLineItem class' do
+ expect(report.line_item_class).to eq(Spree::ReportLineItems::CustomerOrders)
+ end
+ end
+
+ describe '.report_type' do
+ it 'returns the underscored class name' do
+ expect(described_class.report_type).to eq('customer_orders')
+ end
+ end
+end
+```
+
+### Testing the ReportLineItem Class
+
+Test that your line item correctly formats each record:
+
+```ruby spec/models/spree/report_line_items/customer_orders_spec.rb
+require 'rails_helper'
+
+RSpec.describe Spree::ReportLineItems::CustomerOrders, type: :model do
+ let(:store) { create(:store) }
+ let(:user) { create(:admin_user) }
+ let(:bill_address) { create(:address) }
+ let(:order) do
+ create(:completed_order_with_totals,
+ store: store,
+ currency: 'USD',
+ completed_at: 1.week.ago,
+ bill_address: bill_address)
+ end
+
+ let(:report) do
+ Spree::Reports::CustomerOrders.new(
+ store: store,
+ user: user,
+ currency: 'USD',
+ date_from: 1.month.ago,
+ date_to: Time.current
+ )
+ end
+
+ subject(:line_item) { described_class.new(record: order, report: report) }
+
+ describe '#order_number' do
+ it 'returns the order number' do
+ expect(line_item.order_number).to eq(order.number)
+ end
+ end
+
+ describe '#completed_at' do
+ it 'returns formatted completion date' do
+ expect(line_item.completed_at).to eq(order.completed_at.strftime('%Y-%m-%d %H:%M'))
+ end
+ end
+
+ describe '#customer_email' do
+ it 'returns the order email' do
+ expect(line_item.customer_email).to eq(order.email)
+ end
+ end
+
+ describe '#customer_name' do
+ it 'returns the billing address full name' do
+ expect(line_item.customer_name).to eq(bill_address.full_name)
+ end
+
+ context 'when no billing address' do
+ let(:bill_address) { nil }
+
+ it 'returns nil' do
+ order.update_column(:bill_address_id, nil)
+ order.reload
+ expect(line_item.customer_name).to be_nil
+ end
+ end
+ end
+
+ describe '#item_count' do
+ it 'returns the sum of line item quantities' do
+ expected_count = order.line_items.sum(&:quantity)
+ expect(line_item.item_count).to eq(expected_count)
+ end
+ end
+
+ describe '#total' do
+ it 'returns a Spree::Money formatted total' do
+ result = line_item.total
+ expect(result).to be_a(Spree::Money)
+ expect(result.money.to_f).to eq(order.total.to_f)
+ end
+ end
+
+ describe '.headers' do
+ it 'returns headers for all attributes' do
+ headers = described_class.headers
+ header_names = headers.map { |h| h[:name] }
+
+ expect(header_names).to eq(%i[order_number completed_at customer_email customer_name item_count total])
+ end
+ end
+
+ describe '.csv_headers' do
+ it 'returns string keys for CSV output' do
+ expect(described_class.csv_headers).to eq(%w[order_number completed_at customer_email customer_name item_count total])
+ end
+ end
+
+ describe '#to_csv' do
+ it 'returns an array of values for CSV row' do
+ csv_row = line_item.to_csv
+
+ expect(csv_row.length).to eq(6)
+ expect(csv_row[0]).to eq(order.number)
+ expect(csv_row[1]).to eq(order.completed_at.strftime('%Y-%m-%d %H:%M'))
+ expect(csv_row[2]).to eq(order.email)
+ end
+ end
+end
+```
+
+### Testing Reports with Aggregations
+
+For reports that use SQL aggregations, mock the virtual attributes:
+
+```ruby spec/models/spree/report_line_items/revenue_by_category_spec.rb
+require 'rails_helper'
+
+RSpec.describe Spree::ReportLineItems::RevenueByCategory, type: :model do
+ let(:store) { create(:store) }
+ let(:user) { create(:admin_user) }
+ let(:taxonomy) { create(:taxonomy, store: store) }
+ let(:taxon) { create(:taxon, taxonomy: taxonomy, parent: taxonomy.root) }
+
+ let(:report) do
+ Spree::Reports::RevenueByCategory.new(
+ store: store,
+ user: user,
+ currency: 'USD',
+ date_from: 1.month.ago,
+ date_to: Time.current
+ )
+ end
+
+ # Mock the aggregated query result with virtual attributes
+ let(:record) do
+ double(
+ 'AggregatedTaxon',
+ id: taxon.id,
+ name: taxon.name,
+ products: taxon.products,
+ total_quantity: 25,
+ total_revenue: 1250.00,
+ total_tax: 100.00,
+ total_promo: -50.00
+ )
+ end
+
+ subject(:line_item) { described_class.new(record: record, report: report) }
+
+ describe '#category_name' do
+ it 'returns the taxon name' do
+ expect(line_item.category_name).to eq(taxon.name)
+ end
+ end
+
+ describe '#quantity' do
+ it 'returns the total quantity as integer' do
+ expect(line_item.quantity).to eq(25)
+ end
+ end
+
+ describe '#revenue' do
+ it 'returns a Spree::Money formatted revenue' do
+ result = line_item.revenue
+ expect(result).to be_a(Spree::Money)
+ expect(result.money.to_f).to eq(1250.00)
+ end
+ end
+end
+```
+
+### Running the Tests
+
+Run your report specs with:
+
+```bash
+# Run all report specs
+bundle exec rspec spec/models/spree/reports/ spec/models/spree/report_line_items/
+
+# Run a specific report spec
+bundle exec rspec spec/models/spree/reports/customer_orders_spec.rb
+
+# Run with documentation format for detailed output
+bundle exec rspec spec/models/spree/reports/ --format documentation
+```
+
+### Key Testing Patterns
+
+1. **Test scope filtering**: Verify `line_items_scope` returns only records matching date range, currency, and store
+2. **Test line item resolution**: Ensure `line_item_class` resolves to the correct presenter class
+3. **Test registration**: Confirm your report is in `Spree.reports`
+4. **Test attribute formatting**: Verify each attribute method returns correctly formatted data
+5. **Test CSV output**: Check `headers`, `csv_headers`, and `to_csv` return expected values
+6. **Test edge cases**: Handle nil values gracefully (e.g., missing addresses)
+
+## Configuration
+
+### Report Preview Limit
+
+Configure the number of preview rows shown in the admin UI:
+
+```ruby config/initializers/spree.rb
+Spree::Admin::RuntimeConfig.reports_line_items_limit = 100
+```
+
+### Background Job Queue
+
+Reports use a dedicated queue. Configure your job processor:
+
+```ruby
+# Sidekiq example
+Spree.queues.reports = :reports
+```
+
+## Permissions
+
+Report access is controlled by CanCanCan. By default, only users with the `:manage` ability on `Spree::Report` can access reports. Configure permissions in your permission sets.
+
+```ruby
+# Example: Allow all admins to view reports
+can :manage, Spree::Report
+```
diff --git a/docs/docs.json b/docs/docs.json
index 7d346081da..a999ba4741 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -121,7 +121,9 @@
"developer/core-concepts/i18n",
"developer/core-concepts/search-filtering",
"developer/core-concepts/slugs",
- "developer/core-concepts/images-assets"
+ "developer/core-concepts/images-assets",
+ "developer/core-concepts/reports",
+ "developer/core-concepts/imports-exports"
]
},
{