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.

Document the reporting layer and how to extend it

Damian Legawiecef9d71091d12
diff --git a/docs/developer/core-concepts/reporting.mdx b/docs/developer/core-concepts/reporting.mdx
new file mode 100644
index 0000000000..5f289c0ea6
--- /dev/null
+++ b/docs/developer/core-concepts/reporting.mdx
@@ -0,0 +1,192 @@
+---
+title: Reporting
+description: The semantic layer behind the dashboard home screen, the Reports page and saved reports — a registry of metrics and dimensions compiled into one query contract.
+---
+
+## Overview
+
+Spree answers analytics questions through a **semantic layer**: a registry of
+*metrics* (numbers) and *dimensions* (ways to group and filter them), and one
+query contract that compiles a combination of the two into SQL.
+
+Developers extend the vocabulary. Merchants, the dashboard, saved reports and
+future agent tools all compose sentences from it. Nobody writes a report class
+per question.
+
+```mermaid
+flowchart LR
+ R["Spree.reporting<br/>registry"] --> Q["Spree::Reporting::Query<br/>validates + normalizes"]
+ Q --> A["Adapter<br/>(Live: SQL over orders + line items)"]
+ A --> Res["Result<br/>rows + totals"]
+ Res --> API["POST /reporting/query"]
+ R --> S["GET /reporting/schema"]
+ API --> D["Dashboard home,<br/>Reports page,<br/>saved reports, CSV export"]
+ S --> D
+```
+
+## The query contract
+
+A query names what to measure and how to slice it. This is the whole surface:
+
+```json
+{
+ "metrics": ["gross_revenue", "orders_count"],
+ "dimensions": [{ "name": "completed_at", "grain": "week" }],
+ "filters": [{ "dimension": "channel", "op": "eq", "value": "ch_86Rf07xd4z" }],
+ "time_range": { "preset": "last_4_weeks" },
+ "compare": "previous_period",
+ "sort": "-gross_revenue",
+ "limit": 50
+}
+```
+
+| Field | Meaning |
+|-------|---------|
+| `metrics` | One or more registered metric names. Required. |
+| `dimensions` | At most two. A `time` dimension also takes a `grain` (`day`, `week`, `month`). |
+| `filters` | `eq` or `in` against a dimension. Values are prefixed IDs where the dimension identifies a record. |
+| `time_range` | A named preset, or `since`/`until` as ISO 8601. A bare date covers the store's whole day. |
+| `compare` | `previous_period` adds `previous` and `growth` to every metric. |
+| `sort` / `limit` | Ranking controls; ignored for time series, which are always chronological and complete. |
+
+Unknown members are rejected, never dropped. A malformed query answers 422,
+not a partial result computed from the half the server understood.
+
+<Note>
+`GET /api/v3/admin/reporting/schema` returns the vocabulary the **calling
+credential** may use, with labels, per-dimension compatible metrics, filter
+operators, enumerated values and time presets. Build pickers from it rather
+than hardcoding member names — that is how a new dimension reaches the UI
+without a dashboard change.
+</Note>
+
+## Metrics
+
+A metric is an aggregate over one **base** relation, either `:orders` or
+`:line_items`:
+
+```ruby
+Spree.reporting.metric :gross_revenue,
+ sql: 'SUM(%{orders}.total)', base: :orders, format: :money
+```
+
+- `sql` is a portable aggregate fragment. `%{orders}`, `%{line_items}`,
+ `%{variants}`, `%{products}`, `%{addresses}` and `%{product_categories}`
+ interpolate to real table names.
+- `format` is `:money`, `:integer` or `:decimal`. A `:money` metric forces a
+ single-currency scope and arrives with a formatted `display` string.
+- `ratio: [:numerator, :denominator]` defines a **derived** metric, computed
+ after aggregation so it is correct for both rows and totals. Average order
+ value is `ratio: %i[gross_revenue orders_count]`, never `AVG()`.
+
+## Dimensions
+
+A dimension groups and filters. Its definition owns every behaviour keyed off
+it, which is what lets an extension-registered dimension work end to end:
+
+```ruby
+Spree.reporting.dimension :channel, base: :orders, column: :channel_id,
+ lookup: :channel,
+ subject: -> { Spree::Channel }, key_scope: 'read_channels',
+ resolve: ->(store, value) { store.channels.find_by_prefix_id!(value).id },
+ hydrate: lambda { |store, ids, _params|
+ store.channels.where(id: ids).to_h { |c| [c.id, { id: c.prefixed_id, label: c.name, meta: {} }] }
+ }
+```
+
+| Option | Purpose |
+|--------|---------|
+| `base` | `:orders` or `:line_items`. Order-level dimensions are reachable from line items through the order join; not the reverse. |
+| `column` | A column on the base table, or a `%{table}.column` string. Must resolve to a plain identifier. |
+| `joins` | Association joins the grouping needs, applied only to the grouped query. |
+| `type` | `:value` (default) or `:time`. Time dimensions take `grains` and zero-fill buckets. |
+| `lookup` | Tags what the keys identify (`:product`, `:customer`), so clients know display payloads are coming. |
+| `resolve` | Maps a filter's prefixed ID to the raw key, through store-scoped collections. |
+| `hydrate` | Turns raw keys into `{ id:, label:, meta: }` for display. |
+| `subject` / `key_scope` | Authorization — see below. |
+| `values` | Enumerated raw values for status-like dimensions, published as the filter list. |
+
+## Authorization
+
+Reporting never widens what a caller can see. Two axes are enforced together:
+
+- **Staff (JWT)** need `read_reports` plus `:read` on each referenced
+ dimension's `subject`. Order data is always required.
+- **API keys** need `read_reports` plus each dimension's `key_scope`.
+
+Declaring `subject` without `key_scope` raises at registration, so a member
+cannot ship with one axis unguarded. The schema endpoint filters by the same
+rule, so a picker never offers a dimension whose query would be refused.
+
+## What a report counts
+
+Two rules decide what the numbers mean:
+
+**Canceled orders are excluded.** A canceled order keeps its `completed_at`,
+so both bases filter it out. Sales figures count what stayed sold. Refunds are
+unaffected — they already net out of `payment_total`.
+
+**The Total row is the dimensionless figure.** Grouping joins apply only to
+the grouped query; totals run on the base rows with the same filters. A
+product in three categories is counted once in the footer, and an order
+without a shipping address still counts in "Sales by country". A consequence
+worth stating to merchants: **rows of a fan-out breakdown need not sum to the
+total**, and that is correct.
+
+Time buckets resolve in the store's timezone, and a comparison period is the
+range shifted back by its own length, paired bucket by bucket from the start.
+
+## Saved reports
+
+A saved report (`Spree::SavedReport`, prefixed ID `sq_…`) is a stored query
+plus a name, owned by the store and visible to every staff member who may read
+reports. Its visualization is inferred from the query's shape rather than
+configured: a time dimension charts, any other dimension ranks, no dimension
+shows totals.
+
+Nine built-in reports are seeded per store. They are read-only on the model,
+not merely in the UI — copy one to change it.
+
+CSV export rides the existing [export pipeline](/developer/core-concepts/imports-exports)
+as `Spree::Exports::Report`, so it inherits the background job, attachment and
+email. The export re-authorizes its members against the requesting user, which
+is why it requires a user and API keys cannot queue one.
+
+## Relationship to `Spree::Report`
+
+`Spree::Report` still exists and still works. It is a **row-level CSV
+exporter** — one line per record, with attachment and mailer plumbing.
+
+The two answer different questions:
+
+| Question | Use |
+|----------|-----|
+| "Revenue by channel last quarter" | Reporting layer (aggregates, composable) |
+| "Every order line in March, as a spreadsheet" | `Spree::Report` (row-level export) |
+
+New report *types* for analytics are no longer accepted into core: register
+metrics and dimensions instead. See
+[Extend reporting](/developer/how-to/extend-reporting).
+
+## Current limits
+
+Worth knowing before you design an extension:
+
+- **Two bases only.** Metrics aggregate over `:orders` or `:line_items`. A
+ metric declaring another base is refused at query time.
+- **Six interpolatable tables.** The `%{table}` map is fixed; naming a table
+ outside it raises inside the adapter.
+- **Columns are identifiers, not expressions.** A dimension's `column` must
+ resolve to `table.column`; computed groupings such as `SUBSTR(...)` are
+ refused.
+- **The dashboard maps `lookup` to a picker from a fixed list.** A new lookup
+ value still filters correctly, but through a plain ID input.
+
+Reporting on data outside orders and line items therefore needs a core change
+today, not just a registration.
+
+## Related
+
+- [Extend reporting](/developer/how-to/extend-reporting) — a worked example
+- [Imports and exports](/developer/core-concepts/imports-exports) — the CSV pipeline
+- [Permissions](/developer/dashboard/customization/permissions) — `read_reports` and member scopes
diff --git a/docs/developer/how-to/custom-report.mdx b/docs/developer/how-to/custom-report.mdx
deleted file mode 100644
index a9c4fc3a4d..0000000000
--- a/docs/developer/how-to/custom-report.mdx
+++ /dev/null
@@ -1,387 +0,0 @@
----
-title: Build a Custom Report
-description: Step-by-step guide to creating custom reports with data queries, line item formatters, and CSV export.
----
-
-## Overview
-
-Spree's reporting system is designed for extension. Each report is a pair of classes — a **Report** that defines the data query and a **ReportLineItem** that formats each row — registered in `Spree.reports` so it appears in the admin UI.
-
-This guide walks you through building a custom report from scratch, including advanced patterns for SQL aggregations and multi-vendor support.
-
-Before starting, make sure you understand [how the reporting system works](/v5/developer/core-concepts/reports).
-
-## Creating a Custom Report
-
-### Step 1: Create the Report Class
-
-Create a new report class inheriting from `Spree::Report`. The key method to implement is `line_items_scope`, which returns an `ActiveRecord::Relation` defining the records in your report:
-
-```ruby app/models/spree/reports/customer_orders.rb
-module Spree
- module Reports
- class CustomerOrders < Spree::Report
- # Define the scope of records to include in the report
- def line_items_scope
- store.orders.complete.where(
- completed_at: date_from..date_to,
- currency: currency
- ).includes(:user, :bill_address)
- end
- end
- end
-end
-```
-
-The `line_items_scope` method has access to:
-
-| Helper | Description |
-|--------|-------------|
-| `store` | The current store |
-| `date_from` | Report start date |
-| `date_to` | Report end date |
-| `currency` | Report currency |
-| `vendor` | Vendor (if multi-vendor is enabled) |
-
-### Step 2: Create the Line Item Class
-
-Create a corresponding line item class that transforms each record into report columns. The class name must match the report class name (e.g., `Reports::CustomerOrders` → `ReportLineItems::CustomerOrders`):
-
-```ruby app/models/spree/report_line_items/customer_orders.rb
-module Spree
- module ReportLineItems
- class CustomerOrders < Spree::ReportLineItem
- # Define attributes that will become columns
- attribute :order_number, :string
- attribute :completed_at, :string
- attribute :customer_email, :string
- attribute :customer_name, :string
- attribute :item_count, :integer
- attribute :total, :string
-
- # Map record fields to report columns
- def order_number
- record.number
- end
-
- def completed_at
- record.completed_at.strftime('%Y-%m-%d %H:%M')
- end
-
- def customer_email
- record.email
- end
-
- def customer_name
- record.bill_address&.full_name
- end
-
- def item_count
- record.line_items.sum(:quantity)
- end
-
- def total
- Spree::Money.new(record.total, currency: currency)
- end
- end
- end
-end
-```
-
-**Important notes:**
-- Use `attribute` to define columns with their types — these become CSV headers
-- Each attribute needs a corresponding method that extracts/formats data from `record`
-- `record` is a single item from `line_items_scope`
-- Use `Spree::Money` for currency formatting
-- `currency` and `store` are delegated from the report
-
-#### Available Base Class Methods
-
-`Spree::ReportLineItem` provides:
-
-```ruby
-# Returns column headers for display
-self.headers
-# => [{ name: :order_number, label: "Order Number" }, ...]
-
-# Returns column names for CSV header row
-self.csv_headers
-# => ["order_number", "completed_at", "customer_email", ...]
-
-# Converts line item to CSV row array
-to_csv
-# => ["R123456", "2025-01-15 14:30", "[email protected]", ...]
-```
-
-### Step 3: Register the Report
-
-Add your report to the registry in `config/initializers/spree.rb`:
-
-```ruby config/initializers/spree.rb
-Rails.application.config.after_initialize do
- Spree.reports << Spree::Reports::CustomerOrders
-end
-```
-
-### Step 4: Add Translations
-
-Add the report name and column header translations:
-
-```yaml config/locales/en.yml
-en:
- spree:
- report_names:
- customer_orders: Customer Orders
- order_number: Order Number
- completed_at: Completed At
- customer_email: Customer Email
- customer_name: Customer Name
- item_count: Item Count
- total: Total
-```
-
-After restarting your application, the new report will be available in **Admin > Reports**.
-
-## Advanced Patterns
-
-### Complex Queries with Aggregations
-
-For reports that aggregate data across records, use SQL directly in `line_items_scope`:
-
-```ruby app/models/spree/reports/revenue_by_category.rb
-module Spree
- module Reports
- class RevenueByCategory < Spree::Report
- def line_items_scope
- line_items_sql = Spree::LineItem
- .joins(:order)
- .where(
- spree_orders: {
- completed_at: date_from..date_to,
- currency: currency
- }
- )
- .select(
- "spree_line_items.variant_id",
- "SUM(spree_line_items.quantity) as quantity",
- "SUM(spree_line_items.pre_tax_amount) as revenue"
- )
- .group(:variant_id)
- .to_sql
-
- store.taxons
- .where(depth: 1) # Top-level categories
- .joins("LEFT JOIN spree_products_taxons ON spree_products_taxons.taxon_id = spree_taxons.id")
- .joins("LEFT JOIN spree_variants ON spree_variants.product_id = spree_products_taxons.product_id")
- .joins("LEFT JOIN (#{line_items_sql}) AS line_items ON line_items.variant_id = spree_variants.id")
- .select(
- "spree_taxons.*",
- "COALESCE(SUM(line_items.quantity), 0) AS total_quantity",
- "COALESCE(SUM(line_items.revenue), 0.0) AS total_revenue"
- )
- .group("spree_taxons.id")
- end
- end
- end
-end
-```
-
-When using aggregated queries, the `record` in your line item class will have virtual attributes (like `total_quantity`, `total_revenue`) available as methods.
-
-### Custom Summary Section
-
-Override `summary` to provide aggregate metrics alongside the line items:
-
-```ruby app/models/spree/reports/customer_orders.rb
-module Spree
- module Reports
- class CustomerOrders < Spree::Report
- def summary
- {
- total_orders: line_items_scope.count,
- total_revenue: line_items_scope.sum(:total),
- average_order_value: line_items_scope.average(:total)
- }
- end
- end
- end
-end
-```
-
-### Multi-Vendor Support
-
-If you're using Spree Multi-Vendor, filter by vendor when one is selected:
-
-```ruby app/models/spree/reports/vendor_sales.rb
-module Spree
- module Reports
- class VendorSales < Spree::Report
- def line_items_scope
- scope = store.line_items.where(
- order: Spree::Order.complete.where(
- completed_at: date_from..date_to,
- currency: currency
- )
- )
-
- # Filter by vendor if one is selected
- scope = scope.where(vendor_id: vendor.id) if defined?(vendor) && vendor.present?
-
- scope
- end
- end
- end
-end
-```
-
-## Testing Custom Reports
-
-### Testing the Report Class
-
-Test that your report's `line_items_scope` returns the correct records:
-
-```ruby spec/models/spree/reports/customer_orders_spec.rb
-require 'rails_helper'
-
-RSpec.describe Spree::Reports::CustomerOrders, type: :model do
- let(:store) { create(:store) }
- let(:user) { create(:admin_user) }
-
- subject(:report) do
- described_class.new(
- store: store,
- user: user,
- currency: 'USD',
- date_from: 1.month.ago,
- date_to: Time.current
- )
- end
-
- describe '#line_items_scope' do
- let!(:completed_order) do
- create(:completed_order_with_totals, store: store, currency: 'USD', completed_at: 1.week.ago)
- end
-
- let!(:incomplete_order) do
- create(:order, store: store, currency: 'USD', state: 'cart')
- end
-
- let!(:other_currency_order) do
- create(:completed_order_with_totals, store: store, currency: 'EUR', completed_at: 1.week.ago)
- end
-
- let!(:old_order) do
- create(:completed_order_with_totals, store: store, currency: 'USD', completed_at: 2.months.ago)
- end
-
- it 'returns only completed orders within the date range and currency' do
- scope = report.line_items_scope
-
- expect(scope).to include(completed_order)
- expect(scope).not_to include(incomplete_order)
- expect(scope).not_to include(other_currency_order)
- expect(scope).not_to include(old_order)
- end
- end
-
- describe '#line_items' do
- let!(:order) do
- create(:completed_order_with_totals, store: store, currency: 'USD', completed_at: 1.week.ago)
- end
-
- it 'returns ReportLineItem objects' do
- items = report.line_items
- expect(items).to all(be_a(Spree::ReportLineItems::CustomerOrders))
- end
-
- it 'respects the limit option' do
- create(:completed_order_with_totals, store: store, currency: 'USD', completed_at: 2.days.ago)
- items = report.line_items(limit: 1)
- expect(items.length).to eq(1)
- end
- end
-end
-```
-
-### Testing the ReportLineItem Class
-
-Test that your line item correctly formats each record:
-
-```ruby spec/models/spree/report_line_items/customer_orders_spec.rb
-require 'rails_helper'
-
-RSpec.describe Spree::ReportLineItems::CustomerOrders, type: :model do
- let(:store) { create(:store) }
- let(:user) { create(:admin_user) }
- let(:bill_address) { create(:address) }
- let(:order) do
- create(:completed_order_with_totals,
- store: store,
- currency: 'USD',
- completed_at: 1.week.ago,
- bill_address: bill_address)
- end
-
- let(:report) do
- Spree::Reports::CustomerOrders.new(
- store: store,
- user: user,
- currency: 'USD',
- date_from: 1.month.ago,
- date_to: Time.current
- )
- end
-
- subject(:line_item) { described_class.new(record: order, report: report) }
-
- describe '#order_number' do
- it 'returns the order number' do
- expect(line_item.order_number).to eq(order.number)
- end
- end
-
- describe '#customer_name' do
- it 'returns the billing address full name' do
- expect(line_item.customer_name).to eq(bill_address.full_name)
- end
-
- context 'when no billing address' do
- let(:bill_address) { nil }
-
- it 'returns nil' do
- order.update_column(:bill_address_id, nil)
- order.reload
- expect(line_item.customer_name).to be_nil
- end
- end
- end
-
- describe '#total' do
- it 'returns a Spree::Money formatted total' do
- result = line_item.total
- expect(result).to be_a(Spree::Money)
- expect(result.money.to_f).to eq(order.total.to_f)
- end
- end
-
- describe '#to_csv' do
- it 'returns an array of values for CSV row' do
- csv_row = line_item.to_csv
- expect(csv_row.length).to eq(6)
- expect(csv_row[0]).to eq(order.number)
- end
- end
-end
-```
-
-### Key Testing Patterns
-
-1. **Test scope filtering** — verify `line_items_scope` returns only records matching date range, currency, and store
-2. **Test attribute formatting** — verify each attribute method returns correctly formatted data
-3. **Test CSV output** — check `headers`, `csv_headers`, and `to_csv` return expected values
-4. **Test edge cases** — handle nil values gracefully (e.g., missing addresses)
-
-## Related Documentation
-
-- [Reports](/v5/developer/core-concepts/reports) - Report architecture and built-in reports
-- [Events](/developer/core-concepts/events) - How report generation uses the events system
diff --git a/docs/developer/how-to/extend-reporting.mdx b/docs/developer/how-to/extend-reporting.mdx
new file mode 100644
index 0000000000..de1f11a0af
--- /dev/null
+++ b/docs/developer/how-to/extend-reporting.mdx
@@ -0,0 +1,188 @@
+---
+title: Extend Reporting
+description: Register your own metrics and dimensions so merchants can compose them in the Reports builder, saved reports and CSV exports.
+---
+
+## Overview
+
+Reporting is extended by adding *vocabulary*, not by writing report classes.
+Register a metric or a dimension in an initializer and it becomes available
+everywhere at once: the Reports builder, saved reports, CSV export and the
+schema endpoint.
+
+Read [how reporting works](/developer/core-concepts/reporting) first — this
+guide assumes the query contract and the metric/dimension split.
+
+<Note>
+Upgrading from the `Spree::Report` / `ReportLineItem` pattern? That API still
+works for row-level CSV exports and is documented under
+[Build a Custom Report](/v5/developer/how-to/custom-report). For aggregate
+questions, register vocabulary instead.
+</Note>
+
+## Add a metric
+
+A metric is an aggregate over `:orders` or `:line_items`:
+
+```ruby config/initializers/spree.rb
+Rails.application.config.after_initialize do
+ Spree.reporting.metric :items_per_order,
+ sql: 'SUM(%{line_items}.quantity)',
+ base: :line_items,
+ format: :integer
+end
+```
+
+That is the whole change. The metric appears in `GET /reporting/schema`, in
+the builder's metric list, and can be saved into a report.
+
+Give it a label so merchants do not read the raw name:
+
+```yaml config/locales/en.yml
+en:
+ spree:
+ reporting:
+ metrics:
+ items_per_order:
+ label: Items per order
+ description: Units sold divided across orders in the period.
+```
+
+### Derived metrics
+
+A ratio is computed after aggregation, so it stays correct for both rows and
+totals — which a plain `AVG()` would not:
+
+```ruby
+Spree.reporting.metric :average_units_per_order,
+ ratio: %i[units_sold orders_count], format: :decimal
+```
+
+## Add a dimension
+
+A dimension groups and filters. The simplest kind is a column on the base
+table:
+
+```ruby
+Spree.reporting.dimension :order_locale, base: :orders, column: :locale
+```
+
+### A dimension that identifies records
+
+When the keys are IDs rather than plain values, declare four things together:
+how to reach the table, how to resolve a filter value, how to render the key,
+and who may see it.
+
+```ruby
+Spree.reporting.dimension :seller, base: :line_items,
+ column: '%{variants}.seller_id',
+ joins: [:variant],
+ lookup: :seller,
+ subject: -> { Spree::Seller },
+ key_scope: 'read_sellers',
+ resolve: ->(store, value) { store.sellers.find_by_prefix_id!(value).id },
+ hydrate: lambda { |store, ids, _params|
+ store.sellers.where(id: ids).to_h do |seller|
+ [seller.id, { id: seller.prefixed_id, label: seller.name, meta: {} }]
+ end
+ }
+```
+
+What each part buys you:
+
+- `joins` is applied only to the grouped query, so the Total row stays the
+ store's real figure even when the join fans out.
+- `resolve` lets a filter accept the prefixed IDs clients already hold.
+ Scope it through the store, so an ID from another store is a 404.
+- `hydrate` is batched once per dimension per response, not per row.
+- `subject` and `key_scope` are mandatory together. Staff need `:read` on the
+ subject; API keys need the scope. Omitting `key_scope` raises at
+ registration rather than shipping a member that only guards one axis.
+
+### Status-like dimensions
+
+Publish the values so the builder can offer checkboxes instead of a text box:
+
+```ruby
+Spree.reporting.dimension :subscription_state, base: :orders,
+ column: :subscription_state,
+ values: -> { MyExtension::SUBSCRIPTION_STATES }
+```
+
+Use a lambda so model constants load lazily. Label the values under
+`spree.reporting.values.<dimension>.<value>`; they are translated server-side,
+so a plugin needs no dashboard locale edit.
+
+## Verify it
+
+Query the contract directly:
+
+```ruby
+Spree::Reporting::Query.new(
+ store: Spree::Store.default,
+ params: { metrics: %w[items_per_order], dimensions: %w[order_locale] }
+).execute
+```
+
+Or over HTTP:
+
+```bash
+curl -X POST https://example.com/api/v3/admin/reporting/query \
+ -H "X-Spree-API-Key: $SECRET_KEY" -H 'Content-Type: application/json' \
+ -d '{"metrics":["items_per_order"],"dimensions":["order_locale"]}'
+```
+
+A spec is worth writing for the parts that are easy to get wrong — the
+authorization declaration and the hydration payload:
+
+```ruby spec/lib/my_extension/reporting_spec.rb
+RSpec.describe 'seller reporting vocabulary' do
+ let(:store) { @default_store }
+
+ it 'requires the seller subject and scope' do
+ query = Spree::Reporting::Query.new(
+ store: store, params: { metrics: %w[units_sold], dimensions: %w[seller] }
+ )
+
+ expect(query.required_subjects).to include(Spree::Seller)
+ expect(query.required_key_scopes).to include('read_sellers')
+ end
+end
+```
+
+## Overriding a built-in member
+
+Registration refuses a duplicate name unless you say so explicitly:
+
+```ruby
+Spree.reporting.metric :gross_revenue, replace: true,
+ sql: 'SUM(%{orders}.total - %{orders}.delivery_total)',
+ base: :orders, format: :money
+```
+
+Redefining what a built-in number means changes every saved report using it,
+including the seeded ones. Prefer a new name unless you intend exactly that.
+
+## What you cannot do yet
+
+These are limits of the compiler, not of registration:
+
+- **Only `:orders` and `:line_items` are valid bases.** A metric over
+ payments or stock movements is refused at query time.
+- **Only six tables interpolate.** `%{orders}`, `%{line_items}`,
+ `%{variants}`, `%{products}`, `%{addresses}`, `%{product_categories}`.
+ Naming your own table raises inside the adapter.
+- **A dimension's column must be a plain identifier.** Computed groupings
+ such as `SUBSTR(email, ...)` are refused; add a real column, or a database
+ view, if you need one.
+- **Custom `lookup` values fall back to an ID input** in the builder, since
+ the dashboard maps known lookups to pickers.
+
+If your data does not hang off orders or line items, reporting cannot reach it
+today without a core change.
+
+## Related
+
+- [Reporting](/developer/core-concepts/reporting) — the concepts
+- [Permissions](/developer/dashboard/customization/permissions) — scopes and subjects
+- [Build a Custom Report](/v5/developer/how-to/custom-report) — the row-level CSV exporter
diff --git a/docs/docs.json b/docs/docs.json
index 2bf601914d..7187fb8fae 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -390,7 +390,11 @@
},
{
"source": "/developer/core-concepts/reports",
- "destination": "/v5/developer/core-concepts/reports"
+ "destination": "/developer/core-concepts/reporting"
+ },
+ {
+ "source": "/developer/how-to/custom-report",
+ "destination": "/developer/how-to/extend-reporting"
},
{
"source": "/developer/multi-vendor/quickstart",
@@ -538,7 +542,8 @@
"developer/core-concepts/translations",
"developer/core-concepts/slugs",
"developer/core-concepts/metafields",
- "developer/core-concepts/imports-exports"
+ "developer/core-concepts/imports-exports",
+ "developer/core-concepts/reporting"
]
}
],
@@ -742,7 +747,7 @@
]
},
"developer/how-to/custom-promotion",
- "developer/how-to/custom-report",
+ "developer/how-to/extend-reporting",
"developer/how-to/custom-document-numbers",
"developer/how-to/custom-order-routing",
"developer/how-to/custom-stock-splitter"
@@ -1919,7 +1924,8 @@
"developer/core-concepts/translations",
"developer/core-concepts/slugs",
"developer/core-concepts/metafields",
- "developer/core-concepts/imports-exports"
+ "developer/core-concepts/imports-exports",
+ "developer/core-concepts/reporting"
]
}
]
@@ -2065,7 +2071,7 @@
"group": "Reports",
"icon": "chart-bar",
"pages": [
- "developer/how-to/custom-report"
+ "developer/how-to/extend-reporting"
]
},
{