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.

Changed reporting to the industry sales vocabulary

Damian Legawiec11a6263061c1
diff --git a/docs/developer/core-concepts/reporting.mdx b/docs/developer/core-concepts/reporting.mdx
index 5f289c0ea6..5309df3321 100644
--- a/docs/developer/core-concepts/reporting.mdx
+++ b/docs/developer/core-concepts/reporting.mdx
@@ -30,12 +30,12 @@ A query names what to measure and how to slice it. This is the whole surface:
```json
{
- "metrics": ["gross_revenue", "orders_count"],
+ "metrics": ["total_sales", "orders"],
"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",
+ "sort": "-total_sales",
"limit": 50
}
```
@@ -66,18 +66,45 @@ A metric is an aggregate over one **base** relation, either `:orders` or
`:line_items`:
```ruby
-Spree.reporting.metric :gross_revenue,
+Spree.reporting.metric :total_sales,
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.
+ `%{variants}`, `%{products}`, `%{addresses}`, `%{product_categories}`,
+ `%{refunds}`, `%{fees}` and `%{commission_lines}` interpolate to real table
+ names.
+- `format` is `:money`, `:integer`, `:decimal` or `:percent`. A `:money` metric
+ forces a single-currency scope and arrives with a formatted `display` string;
+ a `:percent` metric arrives as the number a merchant reads (`42.5`), not the
+ fraction.
- `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()`.
+ value is `ratio: %i[total_sales orders]`, never `AVG()`.
+
+Money that belongs to an order but lives on another table — refunds,
+commissions — is summed through a **correlated subquery** rather than a join.
+An order with three refunds must stay one row; joining would multiply the base
+row and inflate every other metric in the same query.
+
+### The sales chain
+
+Core's sales metrics follow the sequence merchants and accountants already use,
+so a Spree figure means what the same word means everywhere else:
+
+```
+gross_sales − discounts − returns = net_sales
+net_sales + shipping + duties + fees + taxes = total_sales
+```
+
+`returns` counts money refunded **in the period the refund was issued**, not
+the period of the original order. A report over a past range can therefore
+change after the fact, which is the conventional treatment and the only one an
+open accounting period can produce.
+
+`cost_of_goods`, `gross_profit` and `gross_margin` read the line item's
+`cost_price`. That column is nullable, so a variant with no cost contributes
+zero and margin over an incompletely-costed catalogue reads high.
## Dimensions
@@ -98,6 +125,7 @@ Spree.reporting.dimension :channel, base: :orders, column: :channel_id,
|--------|---------|
| `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. |
+| `expression` | SQL computing the key instead of reading a column — how `customer_type` decides first-time from returning. Use it only where a column genuinely cannot answer; it carries the same trust as a metric's `sql`. |
| `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. |
diff --git a/docs/developer/how-to/extend-reporting.mdx b/docs/developer/how-to/extend-reporting.mdx
index de1f11a0af..15b787b44f 100644
--- a/docs/developer/how-to/extend-reporting.mdx
+++ b/docs/developer/how-to/extend-reporting.mdx
@@ -55,7 +55,7 @@ totals — which a plain `AVG()` would not:
```ruby
Spree.reporting.metric :average_units_per_order,
- ratio: %i[units_sold orders_count], format: :decimal
+ ratio: %i[units_sold orders], format: :decimal
```
## Add a dimension
@@ -155,7 +155,7 @@ end
Registration refuses a duplicate name unless you say so explicitly:
```ruby
-Spree.reporting.metric :gross_revenue, replace: true,
+Spree.reporting.metric :total_sales, replace: true,
sql: 'SUM(%{orders}.total - %{orders}.delivery_total)',
base: :orders, format: :money
```
diff --git a/docs/plans/6.0-analytics-semantic-layer.md b/docs/plans/6.0-analytics-semantic-layer.md
index 14f3314ce1..e49a2437e7 100644
--- a/docs/plans/6.0-analytics-semantic-layer.md
+++ b/docs/plans/6.0-analytics-semantic-layer.md
@@ -1,10 +1,10 @@
# Reporting Semantic Layer
-**Status:** In Progress — Implementation Path Steps 1–9 implemented on `feat/dashboard-reports` (registry + compiler + live adapter + `reporting/query`/`schema` endpoints + member-level permissions + home screen on the contract; Step 7 schema enrichment, Step 8 presets/`week` grain/market·country·variant dimensions/discount·delivery·tax metrics; Step 9 `Spree::SavedReport` + `reporting/saved_reports` CRUD + nine seeded classics + `Spree::Exports::Report` CSV + the Reports SPA pages with the picker builder and inferred visualizations). Rebased onto main 2026-09-03. Step 10 (agent surface) pending.
+**Status:** In Progress — Implementation Path Steps 1–9 implemented on `feat/dashboard-reports` (registry + compiler + live adapter + `reporting/query`/`schema` endpoints + member-level permissions + home screen on the contract; Step 7 schema enrichment, Step 8 presets/`week` grain/market·country·variant dimensions/discount·delivery·tax metrics; Step 9 `Spree::SavedReport` + `reporting/saved_reports` CRUD + nine seeded classics + `Spree::Exports::Report` CSV + the Reports SPA pages with the picker builder and inferred visualizations). Rebased onto main 2026-09-03. Vocabulary reworked to the industry sales chain 2026-09-09 (Decision 14): margin, returns, commission and seller-payout metrics, `seller` and `customer_type` dimensions, permission-gated marketplace metrics. Step 10 (agent surface) pending.
**Target:** Spree 6.0 (core + new dashboard home + Reports page) → 6.1 (facts adapter, AI) — Enterprise ClickHouse adapter out of band
**Depends on:** `6.0-admin-api.md` (v3 conventions), `5.5-admin-api-key-scopes.md` (scope gating), `6.0-multi-vendor-marketplace.md` (vendor forced scope + vendor dashboard consumer), `5.5-admin-api-cli.md` (first agent surface), `5.6-solid-queue-single-container.md` (fact writes + reconciliation jobs)
**Author:** Damian + Claude
-**Last updated:** 2026-09-03 (Steps 7–9 implemented; Decision 13 review rulings)
+**Last updated:** 2026-09-09 (Decision 14: industry sales chain, seller and margin vocabulary)
## Summary
@@ -29,12 +29,12 @@ The 5.6 dashboard work (branch `claude/react-dashboard-home-reporting-71weaz`) i
The extension point is a registry of metrics and dimensions, mirroring `Spree.order_routing.rules` / `Spree::Dependencies`. **Namespace: `Spree.reporting` / `Spree::Reporting`** — `Spree.analytics` / `Spree::Analytics` is already taken by the storefront event-tracking config (`spree/core/lib/spree/analytics.rb`, `AnalyticsConfig`: tracked events + handlers) and stays untouched; "reporting" also matches the merchant-facing Reports nav this plan powers.
```ruby
-Spree.reporting.metric :net_revenue,
+Spree.reporting.metric :net_sales,
sql: "SUM(#{Spree::LineItem.table_name}.pre_tax_amount)",
base: :line_items,
format: :money # money metrics REQUIRE the currency forced scope
-Spree.reporting.metric :orders_count, sql: 'COUNT(DISTINCT spree_orders.id)', base: :orders, format: :integer
+Spree.reporting.metric :orders, sql: 'COUNT(DISTINCT spree_orders.id)', base: :orders, format: :integer
Spree.reporting.dimension :channel, base: :orders, column: :channel_id, lookup: 'Spree::Channel'
Spree.reporting.dimension :category,
@@ -48,12 +48,12 @@ A definition carries: SQL fragment (metrics), join graph, type/format, allowed g
### 2. Query contract stolen from Cube.dev/Lightdash, not invented
```json
-{ "metrics": ["net_revenue", "orders_count"],
+{ "metrics": ["net_sales", "orders"],
"dimensions": [{ "name": "completed_at", "grain": "week" }, "channel"],
"filters": [{ "dimension": "channel", "op": "eq", "value": "ch_x7Yq2k" }],
"time_range": { "since": "-90d" },
"compare": "previous_period",
- "sort": "-net_revenue",
+ "sort": "-net_sales",
"limit": 50 }
```
@@ -121,13 +121,65 @@ Settled while reviewing the implementation, recorded because they change what a
- **Member authorization has one predicate.** `Query#unreadable_subjects(ability)` is what the query endpoint, the export and any future agent tool call; `Registry#compatible?(metric, dimension)` is the one base-compatibility rule the schema and the compiler share.
- **The fulfillment vocabulary is the rollup domain.** The `fulfillment_status` dimension publishes `backorder | canceled | partial | unfulfilled | fulfilled | delivered` — not the legacy `pending/ready/shipped` the model constant still carries for 6.1 removal.
+### 14. The sales vocabulary follows the industry chain (2026-09-09)
+
+A survey of what merchants expect a commerce back office to report (the whole
+catalogue minus marketing and behaviour, which need session data a headless
+storefront does not collect) showed our first nine metrics answer the right
+questions under the wrong names, and leave the two figures merchants ask for
+first — real net revenue and seller payouts — unreachable. Three rulings:
+
+- **Names follow the industry chain, not our columns.** The recognised sequence
+ is `gross_sales − discounts − returns = net_sales`, then
+ `net_sales + shipping + duties + fees + taxes = total_sales`. Our shipped
+ `gross_revenue` was in fact total sales and `net_revenue` was neither term.
+ The vocabulary is renamed to the chain before saved reports bake the wrong
+ names in: `gross_sales`, `discounts`, `returns`, `net_sales`, `shipping`,
+ `duties`, `fees`, `taxes`, `total_sales`. `orders_count` becomes `orders`,
+ `customers_count` becomes `customers`, `aov` becomes `average_order_value`.
+ This is a breaking rename of a vocabulary shipped only on this branch;
+ registered names are public API from the release, so it happens now or never.
+
+- **A returning customer is one with prior orders.** Definitions in the field
+ contradict each other (has-prior-orders versus two-or-more-lifetime). We
+ publish the first: a customer is *returning* on an order when they had at
+ least one earlier completed order, otherwise *first-time*. The distinction is
+ per-order and evaluated against order history, not a stored flag, so it stays
+ correct when history is imported or an order is canceled.
+
+- **Reversals are reported when they happen, so past periods restate.** A
+ refund issued in March against a February order reduces March's `returns` and
+ `net_sales`, not February's. This is the conventional treatment and the only
+ one an unclosed accounting period can produce; the consequence is that a
+ report over a past range can change after the fact, and the docs say so.
+
+Two mechanics follow from the chain:
+
+- Order-level money that lives on another table (refunds, commissions) is
+ aggregated through a **correlated subquery** on the base relation rather than
+ a join, for the same reason grouping joins stay grouped-only (Decision 13):
+ an order with three refunds must stay one row.
+- `cost_of_goods` and `gross_margin` read `line_items.cost_price`, which is
+ nullable — a variant with no cost contributes zero, so margin over an
+ incompletely-costed catalog reads high. The metric documents that rather than
+ guessing a cost.
+
+**Still out of vocabulary reach** (recorded so nobody re-derives them by hand):
+net payments and payment-method breakdowns need a `:payments` base; inventory
+history (units received, sell-through, days of supply) needs a
+`:stock_movements` base over the typed ledger. Both are additive once the
+compiler takes bases from the registry instead of its hardcoded pair — the base
+list and the `resolve_sql` table map are the two closed sets left in the
+compiler. Sessions, referrers and conversion rates stay unavailable: a headless
+storefront does not send us the data.
+
## Design Details
### Registry (`spree/core`)
- `Spree::Reporting::Registry` with `metric(name, **opts)` / `dimension(name, **opts)`, exposed as `Spree.reporting`. Definitions are frozen structs; re-registration under the same name raises outside of an explicit `replace:` flag.
- **Bases** name the root relation the compiler starts from, always store-scoped: `:orders` → `store.orders.complete`, `:line_items` → `store.line_items` (joined through completed orders). A query's members must share a compatible base; the compiler picks the finest.
-- **Starter vocabulary (core-registered):** metrics `net_revenue` (pre_tax_amount), `gross_revenue` (order totals), `orders_count`, `units_sold`, `customers_count` (distinct email), `aov` (derived: `gross_revenue / orders_count`); dimensions `completed_at` (time), `channel`, `category`, `product`, `customer` (grouped by order email, lookup via `store.customers`), `market`, `country`, `payment_status`, `fulfillment_status`; marketplace registers `vendor` when installed. This set is exactly what the new dashboard home consumes — see Implementation Path.
+- **Starter vocabulary (core-registered):** the sales chain (`gross_sales`, `discounts`, `returns`, `net_sales`, `shipping`, `duties`, `fees`, `taxes`, `total_sales` — Decision 14), volume (`orders`, `units_sold`, `customers`, derived `average_order_value`), margin (`cost_of_goods`, `gross_profit`, `gross_margin`) and marketplace (`commission`, `seller_payout`, both permission-gated); dimensions `completed_at` (time), `channel`, `category`, `product`, `variant`, `customer` (grouped by order email, lookup via `store.customers`), `customer_type`, `seller`, `market`, `country`, `payment_status`, `fulfillment_status`. The dashboard home consumes a subset — see Implementation Path.
- **Dimension lookups return display payloads**, not just labels: `{ id, label, meta }` where `meta` comes from the lookup's compact serializer (product → `slug`, `thumbnail_url`, display price; customer → email; channel → name). This is what lets the top-products widget render thumbnails from a generic contract response.
- **Derived metrics** reference other metrics (`aov`), computed post-aggregation so division-by-zero and rounding conventions live in one place (nil-growth convention from the 5.6 dashboard carries over: no baseline → `null`, client renders "New").
@@ -176,7 +228,7 @@ Everything below lands on `claude/react-dashboard-home-reporting-71weaz`. Nothin
### Step 1 — Registry (`spree/core`)
-`Spree::Reporting::Registry` + definition structs, exposed as `Spree.reporting`; core registers the starter vocabulary in the engine initializer. The `net_revenue` SQL is lifted verbatim from `DashboardSerializerHelpers#revenue_sum_sql`, which this step deletes — the module was always the registry's larval form. Unit specs for registration, duplicate-name raising, allowlist introspection.
+`Spree::Reporting::Registry` + definition structs, exposed as `Spree.reporting`; core registers the starter vocabulary in the engine initializer. The `net_sales` SQL is lifted from `DashboardSerializerHelpers#revenue_sum_sql`, which this step deletes — the module was always the registry's larval form. Unit specs for registration, duplicate-name raising, allowlist introspection.
### Step 2 — Compiler + Live adapter (`spree/core`)
@@ -196,10 +248,10 @@ Everything below lands on `claude/react-dashboard-home-reporting-71weaz`. Nothin
| Widget | Query | Powered by |
|---|---|---|
-| KPI tiles + comparison chart | `metrics: [net_revenue, orders_count, aov, units_sold, customers_count]`, `dimensions: [{completed_at, grain: day}]`, `compare: previous_period` | **One request**: `totals` → the five tiles with growth badges; `rows` → both chart series |
-| Rankings → Customers tab | `metrics: [gross_revenue, orders_count]`, `dimensions: [customer]`, `sort: -gross_revenue`, `limit: 5` | `rows` (dimension meta → name/email + customer link) |
-| Rankings → Categories tab | `metrics: [net_revenue, units_sold]`, `dimensions: [category]`, `sort: -net_revenue`, `limit: 5` | `rows` (dimension meta → category link) |
-| Top products | `metrics: [net_revenue, units_sold]`, `dimensions: [product]`, `compare: previous_period`, `sort: -net_revenue`, `limit: 5` | `rows` (+ per-row growth for trend badges; product meta → thumbnail/slug/price) |
+| KPI tiles + comparison chart | `metrics: [total_sales, orders, average_order_value, units_sold, customers]`, `dimensions: [{completed_at, grain: day}]`, `compare: previous_period` | **One request**: `totals` → the five tiles with growth badges; `rows` → both chart series |
+| Rankings → Customers tab | `metrics: [total_sales, orders]`, `dimensions: [customer]`, `sort: -total_sales`, `limit: 5` | `rows` (dimension meta → name/email + customer link) |
+| Rankings → Categories tab | `metrics: [net_sales, units_sold]`, `dimensions: [category]`, `sort: -net_sales`, `limit: 5` | `rows` (dimension meta → category link) |
+| Top products | `metrics: [net_sales, units_sold]`, `dimensions: [product]`, `compare: previous_period`, `sort: -net_sales`, `limit: 5` | `rows` (+ per-row growth for trend badges; product meta → thumbnail/slug/price) |
| Operations card | *(unchanged)* `dashboard.operations` | Point-in-time counts stay bespoke; joins the registry later as "state metrics" if ever |
Chart/tile/ranking-row components become shape-generic (consume `ReportingResult`), which is what the Reports page reuses in Step 7. GrowthBadge, legend, deep-link rows carry over as-is.
@@ -210,7 +262,7 @@ Chart/tile/ranking-row components become shape-generic (consume `ReportingResult
### Step 7 — Schema enrichment (serves the builder and the AI layer in one change)
-`GET /reporting/schema` today returns names only. Both goals need it to carry meaning: `label`/`description` per member (via `Spree.t`, so the picker UI and the tool schema localize from one source), `format` with the store currency for money metrics, per-dimension `compatible_metrics` (the base-compatibility rule the compiler enforces — without it an agent hits `gross_revenue × category` 422s by trial and error), filter `ops` plus enumerated values for status dimensions, the time-range grammar, and `meta` with the store timezone + currency. The payload is **permission-filtered**: members the caller cannot reference (per `required_subjects` / `required_key_scopes`) are omitted, so pickers never offer and agents never propose a member that would 403.
+`GET /reporting/schema` today returns names only. Both goals need it to carry meaning: `label`/`description` per member (via `Spree.t`, so the picker UI and the tool schema localize from one source), `format` with the store currency for money metrics, per-dimension `compatible_metrics` (the base-compatibility rule the compiler enforces — without it an agent hits `total_sales × category` 422s by trial and error), filter `ops` plus enumerated values for status dimensions, the time-range grammar, and `meta` with the store timezone + currency. The payload is **permission-filtered**: members the caller cannot reference (per `required_subjects` / `required_key_scopes`) are omitted, so pickers never offer and agents never propose a member that would 403.
### Step 8 — Time presets + filter vocabulary
@@ -245,7 +297,8 @@ Legacy surfaces: `Spree::Admin::AnalyticsConcern` untouched (legacy admin is mai
- Time-range values are ISO 8601 dates or datetimes (`iso8601`, never `parse`); bare dates cover the store's whole day on either edge and the dashboard sends custom ranges as bare dates.
- **No new hand-rolled aggregate endpoints.** New analytics needs go through the registry + `POST /reporting/query`; `dashboard/operations` (point-in-time counts) is the only bespoke endpoint that stays.
-- **Revenue means `SUM(pre_tax_amount)`** — the `net_revenue` metric is the single definition; do not re-derive it elsewhere.
+- **The sales chain is the vocabulary** (Decision 14): `net_sales` and `total_sales` are the single definitions of revenue; do not re-derive either elsewhere, and do not reintroduce `gross_revenue`/`net_revenue` as names.
+- **Order-level money on another table is a correlated subquery**, never a join on the aggregating scope — an order with three refunds stays one row.
- **New filters are dimensions.** Register a dimension (with `resolve`/`hydrate`/`subject`/`key_scope` when it identifies a resource); never add filter-only parameters to the endpoint.
- **Keep forced-scope discipline**: all analytics queries go through store associations (`store.orders`, `store.line_items`, …), filter exactly one currency, and use `Order.for_channel` for optional channel scoping.
- **Don't add new `Spree::Report` STI subclasses for aggregate questions**; row-level CSV exports only.
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index c07047a668..28ebe4df38 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -49,6 +49,14 @@ yet in the catalog, dropship, consignment, and a quarantine location for rejecte
the first is a buying feature that drags product creation into purchasing, and the rest are
their own plans.
+## 2026-09-09: Reporting speaks the industry sales chain; commission and payout numbers are permission-gated
+
+**Context:** A survey of what merchants expect a commerce back office to report — the whole catalogue minus marketing and behaviour, which need session data a headless storefront never collects — showed the shipped reporting vocabulary answered the right questions under the wrong names. `gross_revenue` was in fact *total sales*, `net_revenue` was neither of the industry's two terms, and the two figures merchants ask for first (real net revenue, and what each seller is owed) could not be expressed at all. Registered names are public API from the release, so a rename had to happen before saved reports baked the wrong ones in.
+
+**Decision:** The vocabulary follows the recognised chain — `gross_sales − discounts − returns = net_sales`, then `net_sales + shipping + duties + fees + taxes = total_sales` — with `orders`, `customers` and `average_order_value` replacing the `*_count`/`aov` names, plus margin (`cost_of_goods`, `gross_profit`, `gross_margin`) and marketplace (`commission`, `seller_payout`) metrics and `seller` / `customer_type` dimensions. A returning customer is one with prior orders, decided per order against history rather than a stored flag. Refunds are reported on the date they were processed, so a past period restates. Order-level money living on another table (refunds, commissions) is summed through a correlated subquery, never a join — an order with three refunds must stay one row. Metrics may now declare `subject`/`key_scope` the way dimensions do, and `commission`/`seller_payout` use it: marketplace money is gated by `read_commissions` / `read_payouts`, not readable by anyone holding `read_reports`.
+
+**Consequences:** The nine seeded reports, the dashboard home's metric list and the reporting specs move together; a store already seeded keeps its old rows, since the seeder only adds what is missing (and a saved report naming a removed metric fails validation loudly rather than silently returning nothing — the upgrade note belongs with the release). A dimension may now carry `expression:` for a computed key, which is how `customer_type` works; `column:` keeps its identifier-only guard. Still out of reach and recorded so nobody hand-rolls them: net payments and payment-method breakdowns need a `:payments` base, inventory history needs a `:stock_movements` base, and both wait on the compiler taking its base list from the registry rather than its hardcoded pair. Sessions, referrers and conversion rates stay unavailable by construction.
+
## 2026-09-07: Inventory operations grooming — transfers get a status and workflows, supplier receives become purchase orders, and a receive records what the units cost
**Context:** `6.0-inventory-operations.md` was written before three things
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index a157446aeb..e6c74112a6 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -75,7 +75,7 @@ export interface ReportingSchemaMetric {
name: string
label: string
description?: string
- format: 'money' | 'integer' | 'decimal' | string
+ format: 'money' | 'integer' | 'decimal' | 'percent' | string
currency?: string
derived: boolean
}
diff --git a/packages/dashboard/src/components/spree/reporting/report-draft.ts b/packages/dashboard/src/components/spree/reporting/report-draft.ts
index 2c662dd5fd..16c5ebeea0 100644
--- a/packages/dashboard/src/components/spree/reporting/report-draft.ts
+++ b/packages/dashboard/src/components/spree/reporting/report-draft.ts
@@ -38,7 +38,7 @@ type ReportViz = 'chart' | 'ranking' | 'stats'
/** What a brand-new report starts from: revenue and orders per day, compared. */
export const EMPTY_QUERY: ReportingQuery = {
- metrics: ['gross_revenue', 'orders_count'],
+ metrics: ['total_sales', 'orders'],
dimensions: [{ name: 'completed_at', grain: 'day' }],
time_range: { preset: DEFAULT_PRESET },
compare: 'previous_period',
diff --git a/packages/dashboard/src/components/spree/reporting/report-view.tsx b/packages/dashboard/src/components/spree/reporting/report-view.tsx
index 8111a05048..126f42eb38 100644
--- a/packages/dashboard/src/components/spree/reporting/report-view.tsx
+++ b/packages/dashboard/src/components/spree/reporting/report-view.tsx
@@ -172,9 +172,11 @@ export function formatMetric(
): string {
if (!value) return '—'
if (value.display) return value.display
- return value.value.toLocaleString(locale, {
+ const formatted = value.value.toLocaleString(locale, {
maximumFractionDigits: metric.format === 'integer' ? 0 : 2,
})
+ // The server sends the number a merchant reads (42.5), so only the sign is missing.
+ return metric.format === 'percent' ? `${formatted}%` : formatted
}
/** Label, formatted total and (when comparing) the period-over-period delta. */
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
index 785cfdad0c..47df2e1176 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
@@ -72,7 +72,7 @@ export const Route = createFileRoute('/_authenticated/$storeId/')({
})
// The five headline metrics, in tile order; labels come from the reporting schema.
-const CHART_METRICS = ['gross_revenue', 'orders_count', 'aov', 'units_sold', 'customers_count']
+const CHART_METRICS = ['total_sales', 'orders', 'average_order_value', 'units_sold', 'customers']
function DashboardPage() {
const { t } = useTranslation()
@@ -361,22 +361,22 @@ const RANKING_QUERIES: Record<
> = {
customers: {
query: {
- metrics: ['gross_revenue', 'orders_count'],
+ metrics: ['total_sales', 'orders'],
dimensions: ['customer'],
- sort: '-gross_revenue',
+ sort: '-total_sales',
limit: 5,
},
- revenueMetric: 'gross_revenue',
- countMetric: 'orders_count',
+ revenueMetric: 'total_sales',
+ countMetric: 'orders',
},
categories: {
query: {
- metrics: ['net_revenue', 'units_sold'],
+ metrics: ['net_sales', 'units_sold'],
dimensions: ['category'],
- sort: '-net_revenue',
+ sort: '-net_sales',
limit: 5,
},
- revenueMetric: 'net_revenue',
+ revenueMetric: 'net_sales',
countMetric: 'units_sold',
},
}
@@ -531,10 +531,10 @@ function TopProducts({ scope }: { scope: Pick<ReportingQuery, 'time_range' | 'fi
const { storeId } = Route.useParams()
const { data: result, isPlaceholderData } = useReportingQuery({
- metrics: ['net_revenue', 'units_sold'],
+ metrics: ['net_sales', 'units_sold'],
dimensions: ['product'],
compare: 'previous_period',
- sort: '-net_revenue',
+ sort: '-net_sales',
limit: 5,
...scope,
})
@@ -566,7 +566,7 @@ function TopProducts({ scope }: { scope: Pick<ReportingQuery, 'time_range' | 'fi
{data.rows.map((row) => {
const product = entityDimension(row, 'product')
const productId = product.id
- const revenue = row.metrics.net_revenue
+ const revenue = row.metrics.net_sales
const thumbnail = metaString(product, 'thumbnail_url') ?? null
const price = metaString(product, 'price')
diff --git a/spree/api/app/controllers/spree/api/v3/admin/reporting_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/reporting_controller.rb
index d25c1579b5..2f5730fe33 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/reporting_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/reporting_controller.rb
@@ -34,7 +34,7 @@ module Spree
def schema
render json: Spree::Reporting::Schema.new(
store: current_store,
- allowed: ->(dimension) { dimension_allowed?(dimension) }
+ allowed: ->(member) { member_allowed?(member) }
).to_h
end
@@ -74,11 +74,13 @@ module Spree
end
end
- def dimension_allowed?(dimension)
+ # Metrics and dimensions declare authorization the same way, so one
+ # predicate answers for both.
+ def member_allowed?(member)
if current_api_key.present?
- dimension.key_scope.blank? || current_api_key.has_scope?(dimension.key_scope)
+ member.key_scope.blank? || current_api_key.has_scope?(member.key_scope)
else
- dimension.subject.nil? || can?(:read, dimension.subject.call)
+ member.subject.nil? || can?(:read, member.subject.call)
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/reporting/saved_reports_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/reporting/saved_reports_controller_spec.rb
index 52eab84f3b..b71ff7b9e0 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/reporting/saved_reports_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/reporting/saved_reports_controller_spec.rb
@@ -7,7 +7,7 @@ RSpec.describe Spree::Api::V3::Admin::Reporting::SavedReportsController, type: :
before { request.headers.merge!(headers) }
- let(:query) { { 'metrics' => %w[gross_revenue orders_count], 'dimensions' => %w[channel], 'sort' => '-gross_revenue' } }
+ let(:query) { { 'metrics' => %w[total_sales orders], 'dimensions' => %w[channel], 'sort' => '-total_sales' } }
let!(:report) { create(:saved_report, store: store, name: 'Sales by channel', query: query) }
describe 'GET #index' do
@@ -24,16 +24,16 @@ RSpec.describe Spree::Api::V3::Admin::Reporting::SavedReportsController, type: :
describe 'POST #create' do
it 'saves a compilable query and records the author' do
- post :create, params: { name: 'Top products', query: { metrics: %w[net_revenue], dimensions: %w[product], limit: 10 } }, as: :json
+ post :create, params: { name: 'Top products', query: { metrics: %w[net_sales], dimensions: %w[product], limit: 10 } }, as: :json
expect(response).to have_http_status(:created)
- expect(json_response['query']['metrics']).to eq(%w[net_revenue])
+ expect(json_response['query']['metrics']).to eq(%w[net_sales])
expect(json_response['seeded']).to be false
expect(json_response['author_name']).to be_present
end
it 'rejects a query the registry cannot compile' do
- post :create, params: { name: 'Broken', query: { metrics: %w[gross_revenue], dimensions: %w[category] } }, as: :json
+ post :create, params: { name: 'Broken', query: { metrics: %w[total_sales], dimensions: %w[category] } }, as: :json
expect(response).to have_http_status(:unprocessable_content)
expect(response.body).to include('cannot be grouped')
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/reporting_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/reporting_controller_spec.rb
index 82a506c2ad..5bcb80fb31 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/reporting_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/reporting_controller_spec.rb
@@ -11,7 +11,7 @@ RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
it 'hydrates enumerated dimensions with labels' do
create(:completed_order_with_totals, store: store, completed_at: 2.days.ago).update_columns(payment_status: 'partially_paid')
- post :query, params: { metrics: %w[orders_count], dimensions: %w[payment_status] }, as: :json
+ post :query, params: { metrics: %w[orders], dimensions: %w[payment_status] }, as: :json
expect(response).to have_http_status(:ok)
expect(json_response['rows'].first['dimensions']['payment_status']).to eq('id' => 'partially_paid', 'label' => 'Partially paid', 'meta' => {})
@@ -21,7 +21,7 @@ RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
let(:query_params) do
{
- metrics: %w[gross_revenue orders_count aov],
+ metrics: %w[total_sales orders average_order_value],
dimensions: [{ name: 'completed_at', grain: 'day' }],
compare: 'previous_period'
}
@@ -31,7 +31,7 @@ RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
subject
expect(response).to have_http_status(:ok)
expect(json_response['meta']).to include('currency', 'time_range', 'previous_time_range', 'metrics', 'dimensions')
- expect(json_response['totals'].keys).to match_array(%w[gross_revenue orders_count aov])
+ expect(json_response['totals'].keys).to match_array(%w[total_sales orders average_order_value])
expect(json_response['rows'].length).to eq(31) # default 30 days + today
end
@@ -44,18 +44,18 @@ RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
totals = json_response['totals']
expected_gross = (order1.total + order2.total).to_f.round(2)
- expect(totals['gross_revenue']['value']).to eq(expected_gross)
- expect(totals['gross_revenue']['display']).to include('$')
- expect(totals['gross_revenue']['growth']).to be_nil
- expect(totals['orders_count']['value']).to eq(2)
- expect(totals['aov']['value']).to eq((expected_gross / 2).round(2))
+ expect(totals['total_sales']['value']).to eq(expected_gross)
+ expect(totals['total_sales']['display']).to include('$')
+ expect(totals['total_sales']['growth']).to be_nil
+ expect(totals['orders']['value']).to eq(2)
+ expect(totals['average_order_value']['value']).to eq((expected_gross / 2).round(2))
end
it 'hydrates product rows with prefixed ids, labels and meta' do
post :query, params: {
- metrics: %w[net_revenue units_sold],
+ metrics: %w[net_sales units_sold],
dimensions: %w[product],
- sort: '-net_revenue',
+ sort: '-net_sales',
limit: 5
}, as: :json
@@ -63,14 +63,14 @@ RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
expect(row['dimensions']['product']['id']).to start_with('prod_')
expect(row['dimensions']['product']['label']).to be_present
expect(row['dimensions']['product']['meta']).to include('slug', 'thumbnail_url')
- expect(row['metrics']['net_revenue']['value']).to be > 0
+ expect(row['metrics']['net_sales']['value']).to be > 0
end
it 'hydrates customer rows and ranks by revenue' do
post :query, params: {
- metrics: %w[gross_revenue orders_count],
+ metrics: %w[total_sales orders],
dimensions: %w[customer],
- sort: '-gross_revenue',
+ sort: '-total_sales',
limit: 5
}, as: :json
@@ -78,7 +78,7 @@ RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
top = json_response['rows'].first
expect(top['dimensions']['customer']['id']).to start_with('cust_')
expect(top['dimensions']['customer']['meta']['email']).to be_present
- expect(top['metrics']['orders_count']['value']).to eq(1)
+ expect(top['metrics']['orders']['value']).to eq(1)
end
it 'filters by channel' do
@@ -86,18 +86,18 @@ RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
create(:completed_order_with_totals, store: store, channel: channel, completed_at: 3.days.ago)
post :query, params: {
- metrics: %w[orders_count],
+ metrics: %w[orders],
filters: [{ dimension: 'channel', op: 'eq', value: channel.prefixed_id }]
}, as: :json
- expect(json_response['totals']['orders_count']['value']).to eq(1)
+ expect(json_response['totals']['orders']['value']).to eq(1)
end
it 'returns 404 for a channel filter from another store' do
foreign_channel = create(:channel, store: create(:store))
post :query, params: {
- metrics: %w[orders_count],
+ metrics: %w[orders],
filters: [{ dimension: 'channel', op: 'eq', value: foreign_channel.prefixed_id }]
}, as: :json
@@ -111,7 +111,7 @@ RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
expect(response).to have_http_status(:unprocessable_content)
expect(json_response['error']['code']).to eq('invalid_reporting_query')
- expect(json_response['error']['message']).to include('net_revenue')
+ expect(json_response['error']['message']).to include('net_sales')
end
it 'names the valid members in the error details so a client can correct itself' do
post :query, params: { metrics: %w[revenue] }, as: :json
@@ -120,7 +120,7 @@ RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
details = json_response['error']['details']
expect(details['kind']).to eq('metric')
expect(details['name']).to eq('revenue')
- expect(details['valid']).to include('gross_revenue', 'net_revenue')
+ expect(details['valid']).to include('total_sales', 'net_sales')
end
end
@@ -140,12 +140,12 @@ RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
let(:reports_key) { create(:api_key, :secret, store: store, scopes: %w[read_reports]) }
it 'allows order-data queries with read_reports alone' do
- post :query, params: { metrics: %w[gross_revenue orders_count] }, as: :json
+ post :query, params: { metrics: %w[total_sales orders] }, as: :json
expect(response).to have_http_status(:ok)
end
it 'forbids members whose key_scope the key lacks' do
- post :query, params: { metrics: %w[net_revenue], dimensions: %w[product] }, as: :json
+ post :query, params: { metrics: %w[net_sales], dimensions: %w[product] }, as: :json
expect(response).to have_http_status(:forbidden)
expect(json_response['error']['details']['required_scopes']).to eq(%w[read_products])
@@ -155,7 +155,7 @@ RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
key = create(:api_key, :secret, store: store, scopes: %w[read_reports read_products])
request.headers['x-spree-api-key'] = key.plaintext_token
- post :query, params: { metrics: %w[net_revenue], dimensions: %w[product] }, as: :json
+ post :query, params: { metrics: %w[net_sales], dimensions: %w[product] }, as: :json
expect(response).to have_http_status(:ok)
end
end
@@ -167,21 +167,21 @@ RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
let(:custom_permissions) { %w[read_reports read_orders] }
it 'allows order-data queries' do
- post :query, params: { metrics: %w[gross_revenue orders_count] }, as: :json
+ post :query, params: { metrics: %w[total_sales orders] }, as: :json
expect(response).to have_http_status(:ok)
end
it 'forbids dimensions whose subject the role cannot read' do
- post :query, params: { metrics: %w[net_revenue], dimensions: %w[product] }, as: :json
+ post :query, params: { metrics: %w[net_sales], dimensions: %w[product] }, as: :json
expect(response).to have_http_status(:forbidden)
- post :query, params: { metrics: %w[gross_revenue], dimensions: %w[customer] }, as: :json
+ post :query, params: { metrics: %w[total_sales], dimensions: %w[customer] }, as: :json
expect(response).to have_http_status(:forbidden)
end
it 'forbids filters whose subject the role cannot read' do
post :query, params: {
- metrics: %w[net_revenue],
+ metrics: %w[net_sales],
filters: [{ dimension: 'product', op: 'eq', value: 'prod_x' }]
}, as: :json
@@ -194,7 +194,7 @@ RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
get :schema, as: :json
expect(response).to have_http_status(:ok)
- metric = json_response['metrics'].find { |m| m['name'] == 'gross_revenue' }
+ metric = json_response['metrics'].find { |m| m['name'] == 'total_sales' }
expect(metric).to include('label', 'description', 'format', 'currency')
dimension = json_response['dimensions'].find { |d| d['name'] == 'completed_at' }
expect(dimension['grains']).to include('day', 'week', 'month')
diff --git a/spree/core/app/services/spree/seeds/saved_reports.rb b/spree/core/app/services/spree/seeds/saved_reports.rb
index 5a24fec6ab..128578b9cc 100644
--- a/spree/core/app/services/spree/seeds/saved_reports.rb
+++ b/spree/core/app/services/spree/seeds/saved_reports.rb
@@ -9,31 +9,46 @@ module Spree
REPORTS = [
{ key: 'sales_over_time',
- query: { 'metrics' => %w[gross_revenue orders_count aov], 'dimensions' => [{ 'name' => 'completed_at', 'grain' => 'day' }],
+ query: { 'metrics' => %w[total_sales orders average_order_value], 'dimensions' => [{ 'name' => 'completed_at', 'grain' => 'day' }],
'time_range' => { 'preset' => 'last_4_weeks' }, 'compare' => 'previous_period' } },
+ { key: 'net_sales_over_time',
+ query: { 'metrics' => %w[gross_sales discounts returns net_sales], 'dimensions' => [{ 'name' => 'completed_at', 'grain' => 'week' }],
+ 'time_range' => { 'preset' => 'last_12_months' }, 'compare' => 'previous_period' } },
{ key: 'sales_by_channel',
- query: { 'metrics' => %w[gross_revenue orders_count], 'dimensions' => %w[channel],
- 'time_range' => { 'preset' => 'last_4_weeks' }, 'sort' => '-gross_revenue' } },
+ query: { 'metrics' => %w[total_sales orders], 'dimensions' => %w[channel],
+ 'time_range' => { 'preset' => 'last_4_weeks' }, 'sort' => '-total_sales' } },
{ key: 'sales_by_market',
- query: { 'metrics' => %w[gross_revenue orders_count], 'dimensions' => %w[market],
- 'time_range' => { 'preset' => 'last_4_weeks' }, 'sort' => '-gross_revenue' } },
+ query: { 'metrics' => %w[total_sales orders], 'dimensions' => %w[market],
+ 'time_range' => { 'preset' => 'last_4_weeks' }, 'sort' => '-total_sales' } },
{ key: 'sales_by_country',
- query: { 'metrics' => %w[gross_revenue orders_count], 'dimensions' => %w[country],
- 'time_range' => { 'preset' => 'last_4_weeks' }, 'sort' => '-gross_revenue' } },
+ query: { 'metrics' => %w[total_sales orders], 'dimensions' => %w[country],
+ 'time_range' => { 'preset' => 'last_4_weeks' }, 'sort' => '-total_sales' } },
{ key: 'top_products',
- query: { 'metrics' => %w[net_revenue units_sold], 'dimensions' => %w[product],
- 'time_range' => { 'preset' => 'last_4_weeks' }, 'sort' => '-net_revenue', 'limit' => 20 } },
+ query: { 'metrics' => %w[net_sales units_sold], 'dimensions' => %w[product],
+ 'time_range' => { 'preset' => 'last_4_weeks' }, 'sort' => '-net_sales', 'limit' => 20 } },
{ key: 'top_categories',
- query: { 'metrics' => %w[net_revenue units_sold], 'dimensions' => %w[category],
- 'time_range' => { 'preset' => 'last_4_weeks' }, 'sort' => '-net_revenue', 'limit' => 20 } },
+ query: { 'metrics' => %w[net_sales units_sold], 'dimensions' => %w[category],
+ 'time_range' => { 'preset' => 'last_4_weeks' }, 'sort' => '-net_sales', 'limit' => 20 } },
{ key: 'top_customers',
- query: { 'metrics' => %w[gross_revenue orders_count], 'dimensions' => %w[customer],
- 'time_range' => { 'preset' => 'last_4_weeks' }, 'sort' => '-gross_revenue', 'limit' => 20 } },
+ query: { 'metrics' => %w[total_sales orders], 'dimensions' => %w[customer],
+ 'time_range' => { 'preset' => 'last_4_weeks' }, 'sort' => '-total_sales', 'limit' => 20 } },
+ { key: 'product_margin',
+ query: { 'metrics' => %w[net_sales cost_of_goods gross_profit gross_margin], 'dimensions' => %w[product],
+ 'time_range' => { 'preset' => 'last_4_weeks' }, 'sort' => '-gross_profit', 'limit' => 20 } },
+ { key: 'returns_over_time',
+ query: { 'metrics' => %w[returns orders], 'dimensions' => [{ 'name' => 'completed_at', 'grain' => 'month' }],
+ 'time_range' => { 'preset' => 'last_12_months' }, 'compare' => 'previous_period' } },
+ { key: 'first_time_vs_returning',
+ query: { 'metrics' => %w[total_sales orders customers], 'dimensions' => %w[customer_type],
+ 'time_range' => { 'preset' => 'last_4_weeks' }, 'compare' => 'previous_period' } },
+ { key: 'seller_payouts',
+ query: { 'metrics' => %w[net_sales commission seller_payout units_sold], 'dimensions' => %w[seller],
+ 'time_range' => { 'preset' => 'last_month' }, 'sort' => '-seller_payout', 'limit' => 50 } },
{ key: 'orders_by_payment_status',
- query: { 'metrics' => %w[orders_count gross_revenue], 'dimensions' => %w[payment_status],
+ query: { 'metrics' => %w[orders total_sales], 'dimensions' => %w[payment_status],
'time_range' => { 'preset' => 'last_4_weeks' } } },
{ key: 'orders_by_fulfillment_status',
- query: { 'metrics' => %w[orders_count gross_revenue], 'dimensions' => %w[fulfillment_status],
+ query: { 'metrics' => %w[orders total_sales], 'dimensions' => %w[fulfillment_status],
'time_range' => { 'preset' => 'last_4_weeks' } } }
].freeze
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 1cb993465f..9a57174d94 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -1701,6 +1701,9 @@ en:
customer:
description: The customer who placed the order, by email.
label: Customer
+ customer_type:
+ description: Whether the buyer had placed an earlier order at the time of this one.
+ label: Customer type
fulfillment_status:
description: Fulfillment state of the order.
label: Fulfillment status
@@ -1713,36 +1716,66 @@ en:
product:
description: The product sold.
label: Product
+ seller:
+ description: The seller who sold the item.
+ label: Seller
variant:
description: The product variant (SKU) sold.
label: Variant
export:
total: Total
metrics:
- aov:
+ average_order_value:
description: Total sales divided by the number of orders.
label: Average order value
- customers_count:
+ commission:
+ description: What the marketplace earned on these sales, including its tax.
+ label: Commission
+ cost_of_goods:
+ description: What the goods sold cost you. Variants with no cost price count as zero.
+ label: Cost of goods
+ customers:
description: Distinct customer emails that placed orders.
label: Customers
- delivery_total:
- description: Sum of delivery charges.
- label: Delivery
- discounts_total:
- description: Sum of order discounts.
+ discounts:
+ description: Discounts applied to the items sold.
label: Discounts
- gross_revenue:
- description: Sum of order totals (items, delivery and tax, after discounts).
- label: Total sales
- net_revenue:
- description: Line item revenue after discounts and net of included taxes.
- label: Net revenue
- orders_count:
+ duties:
+ description: Customs duties charged on the order.
+ label: Duties
+ fees:
+ description: Shopper-visible fees other than duties.
+ label: Fees
+ gross_margin:
+ description: Gross profit as a share of net sales.
+ label: Gross margin
+ gross_profit:
+ description: Net sales less the cost of the goods sold.
+ label: Gross profit
+ gross_sales:
+ description: Item prices multiplied by quantity, before discounts, returns and tax.
+ label: Gross sales
+ net_sales:
+ description: Gross sales less discounts and returns. What you actually sold.
+ label: Net sales
+ orders:
description: Number of placed orders.
label: Orders
- tax_total:
+ returns:
+ description: Money refunded, counted in the period the refund was issued.
+ label: Returns
+ seller_payout:
+ description: What the sellers are owed on these sales, after commission.
+ label: Seller payout
+ shipping:
+ description: Delivery charged to the customer.
+ label: Shipping
+ taxes:
description: Sum of additional and included taxes.
- label: Tax
+ label: Taxes
+ total_sales:
+ description: Net sales plus shipping, duties, fees and taxes. The money taken.
+ label: Total sales
units_sold:
description: Sum of line item quantities.
label: Units sold
@@ -1776,12 +1809,24 @@ en:
yesterday:
label: Yesterday
seeds:
+ first_time_vs_returning:
+ description: Sales split between first-time and returning buyers over the last four weeks.
+ name: First-time vs returning
+ net_sales_over_time:
+ description: Weekly gross sales, discounts, returns and net sales over the last twelve months.
+ name: Net sales over time
orders_by_fulfillment_status:
description: Order counts and sales grouped by fulfillment status over the last four weeks.
name: Orders by fulfillment status
orders_by_payment_status:
description: Order counts and sales grouped by payment status over the last four weeks.
name: Orders by payment status
+ product_margin:
+ description: Products ranked by gross profit over the last four weeks, with cost and margin.
+ name: Product margin
+ returns_over_time:
+ description: Monthly refunds over the last twelve months, compared with the previous period.
+ name: Returns over time
sales_by_channel:
description: Sales and orders per sales channel over the last four weeks.
name: Sales by channel
@@ -1794,14 +1839,17 @@ en:
sales_over_time:
description: Daily sales, orders and average order value for the last four weeks, compared with the previous period.
name: Sales over time
+ seller_payouts:
+ description: What each seller earned last month, after the marketplace commission.
+ name: Seller payouts
top_categories:
- description: Best-selling categories by net revenue over the last four weeks.
+ description: Best-selling categories by net sales over the last four weeks.
name: Top categories
top_customers:
description: Customers ranked by spend over the last four weeks.
name: Top customers
top_products:
- description: Best-selling products by net revenue over the last four weeks.
+ description: Best-selling products by net sales over the last four weeks.
name: Top products
unassigned: Unassigned
values:
diff --git a/spree/core/lib/spree/reporting/adapters/base.rb b/spree/core/lib/spree/reporting/adapters/base.rb
index d7f586a2bd..c3048321d1 100644
--- a/spree/core/lib/spree/reporting/adapters/base.rb
+++ b/spree/core/lib/spree/reporting/adapters/base.rb
@@ -22,7 +22,7 @@ module Spree
def cast_value(metric, raw)
case metric.format
- when :money, :decimal then raw.to_f.round(2)
+ when :money, :decimal, :percent then raw.to_f.round(2)
else raw.to_i
end
end
@@ -35,7 +35,11 @@ module Spree
def apply_derived(metrics)
query.metrics.select(&:derived?).each do |metric|
numerator, denominator = metric.ratio.map { |name| metrics[name] || 0 }
- metrics[metric.name] = denominator.to_f.zero? ? 0.0 : (numerator / denominator.to_f).round(2)
+ ratio = denominator.to_f.zero? ? 0.0 : numerator / denominator.to_f
+ # A percent metric carries the number a merchant reads (42.5), not
+ # the fraction, so clients never have to know to multiply.
+ ratio *= 100 if metric.format == :percent
+ metrics[metric.name] = ratio.round(2)
end
end
diff --git a/spree/core/lib/spree/reporting/adapters/live.rb b/spree/core/lib/spree/reporting/adapters/live.rb
index f84c1de6ae..f024e22665 100644
--- a/spree/core/lib/spree/reporting/adapters/live.rb
+++ b/spree/core/lib/spree/reporting/adapters/live.rb
@@ -212,7 +212,10 @@ module Spree
variants: Spree::Variant.table_name,
products: Spree::Product.table_name,
addresses: Spree::Address.table_name,
- product_categories: Spree::ProductCategory.table_name)
+ product_categories: Spree::ProductCategory.table_name,
+ refunds: Spree::Refund.table_name,
+ fees: Spree::Fee.table_name,
+ commission_lines: Spree::CommissionLine.table_name)
end
def dimension_alias(dim)
@@ -232,6 +235,8 @@ module Spree
# like `table.column` and nothing else. Anything richer is a
# registration bug and raises rather than reaching the database.
def qualified_column(dimension)
+ return resolve_sql(dimension.expression) if dimension.expression?
+
resolved = if dimension.column.is_a?(String)
resolve_sql(dimension.column)
else
diff --git a/spree/core/lib/spree/reporting/default_vocabulary.rb b/spree/core/lib/spree/reporting/default_vocabulary.rb
index 0c0a74d95b..32bf9da231 100644
--- a/spree/core/lib/spree/reporting/default_vocabulary.rb
+++ b/spree/core/lib/spree/reporting/default_vocabulary.rb
@@ -8,18 +8,111 @@ module Spree
# Model classes appear only inside lambdas and %{table} placeholders —
# nothing here may autoload during initialization.
module DefaultVocabulary
+ # Order-level money that lives on another table. Correlated on the
+ # order's own id so the aggregate stays one value per order — joining
+ # would multiply the base row and inflate every other metric in the
+ # same query.
+ REFUNDS_SUBQUERY = <<~SQL.squish.freeze
+ SUM(COALESCE((SELECT SUM(r.amount) FROM %{refunds} r WHERE r.order_id = %{orders}.id), 0))
+ SQL
+
+ # A refund is issued against the order, not a line, so it is apportioned
+ # by the line's share of the order's pre-tax value.
+ LINE_ITEM_REFUNDS_SUBQUERY = <<~SQL.squish.freeze
+ SUM(
+ COALESCE((SELECT SUM(r.amount) FROM %{refunds} r WHERE r.order_id = %{orders}.id), 0)
+ * CASE WHEN %{orders}.item_total > 0 THEN %{line_items}.pre_tax_amount / %{orders}.item_total ELSE 0 END
+ )
+ SQL
+
+ # An order is the customer's first when no earlier completed order shares
+ # its email in the same store.
+ CUSTOMER_TYPE_SQL = <<~SQL.squish.freeze
+ CASE WHEN EXISTS (
+ SELECT 1 FROM %{orders} prior
+ WHERE prior.email = %{orders}.email
+ AND prior.store_id = %{orders}.store_id
+ AND prior.status <> 'canceled'
+ AND prior.completed_at IS NOT NULL
+ AND prior.completed_at < %{orders}.completed_at
+ ) THEN 'returning' ELSE 'first_time' END
+ SQL
+
+ DUTIES_SUBQUERY = <<~SQL.squish.freeze
+ SUM(COALESCE((SELECT SUM(f.amount) FROM %{fees} f
+ WHERE f.order_id = %{orders}.id AND f.kind = 'duty'), 0))
+ SQL
+
+ SELLER_COMMISSION_SUBQUERY = <<~SQL.squish.freeze
+ SUM(COALESCE((SELECT SUM(c.total) FROM %{commission_lines} c
+ WHERE c.line_item_id = %{line_items}.id), 0))
+ SQL
+
def self.install(registry)
registry.instance_eval do
- metric :gross_revenue, sql: 'SUM(%{orders}.total)', base: :orders, format: :money
- metric :net_revenue, sql: 'SUM(%{line_items}.pre_tax_amount)', base: :line_items, format: :money
- metric :orders_count, sql: 'COUNT(*)', base: :orders, format: :integer
+ # ---- the sales chain ----
+ #
+ # gross_sales - discounts - returns = net_sales
+ # net_sales + shipping + duties + fees + taxes = total_sales
+ #
+ # Line-item money is the finest grain we hold, so the first three
+ # terms aggregate on :line_items and the order-level charges on
+ # :orders. Money that lives on another table (refunds, commissions)
+ # is summed through a correlated subquery: an order with three
+ # refunds must stay one row.
+
+ metric :gross_sales, sql: 'SUM(%{line_items}.price * %{line_items}.quantity)',
+ base: :line_items, format: :money
+ metric :discounts, sql: 'SUM(%{line_items}.discount_total)', base: :line_items, format: :money
+ metric :returns, sql: REFUNDS_SUBQUERY, base: :orders, format: :money
+ # Net of returns as well as discounts, so this is the figure a
+ # merchant recognises as "what we actually sold".
+ metric :net_sales, sql: "SUM(%{line_items}.pre_tax_amount) - #{LINE_ITEM_REFUNDS_SUBQUERY}",
+ base: :line_items, format: :money
+ metric :shipping, sql: 'SUM(%{orders}.delivery_total)', base: :orders, format: :money
+ metric :duties, sql: DUTIES_SUBQUERY, base: :orders, format: :money
+ # Every shopper-visible fee except duties, which the chain counts separately.
+ metric :fees, sql: "SUM(COALESCE(%{orders}.fee_total, 0)) - #{DUTIES_SUBQUERY}",
+ base: :orders, format: :money
+ metric :taxes, sql: 'SUM(%{orders}.additional_tax_total + %{orders}.included_tax_total)',
+ base: :orders, format: :money
+ # The order grand total, net of what came back.
+ metric :total_sales, sql: "SUM(%{orders}.total) - #{REFUNDS_SUBQUERY}",
+ base: :orders, format: :money
+
+ # ---- volume ----
+
+ metric :orders, sql: 'COUNT(*)', base: :orders, format: :integer
metric :units_sold, sql: 'SUM(%{line_items}.quantity)', base: :line_items, format: :integer
- metric :customers_count, sql: 'COUNT(DISTINCT %{orders}.email)', base: :orders, format: :integer
- metric :aov, ratio: %i[gross_revenue orders_count], format: :money
- metric :discounts_total, sql: 'SUM(%{orders}.discount_total)', base: :orders, format: :money
- metric :delivery_total, sql: 'SUM(%{orders}.delivery_total)', base: :orders, format: :money
- metric :tax_total, sql: 'SUM(%{orders}.additional_tax_total + %{orders}.included_tax_total)',
- base: :orders, format: :money
+ metric :customers, sql: 'COUNT(DISTINCT %{orders}.email)', base: :orders, format: :integer
+ metric :average_order_value, ratio: %i[total_sales orders], format: :money
+
+ # ---- margin ----
+ #
+ # cost_price is nullable, so an uncosted variant contributes zero and
+ # margin over an incompletely-costed catalogue reads high. Guessing a
+ # cost would be worse than reporting the gap.
+ metric :cost_of_goods, sql: 'SUM(COALESCE(%{line_items}.cost_price, 0) * %{line_items}.quantity)',
+ base: :line_items, format: :money
+ metric :gross_profit,
+ sql: 'SUM(%{line_items}.pre_tax_amount) - SUM(COALESCE(%{line_items}.cost_price, 0) * %{line_items}.quantity)',
+ base: :line_items, format: :money
+ metric :gross_margin, ratio: %i[gross_profit net_sales], format: :percent
+
+ # ---- marketplace ----
+ #
+ # A commission is a platform-to-seller settlement, never part of what
+ # the shopper paid. Summed from the lines rather than the order's
+ # denormalized total so it can be broken down by seller — an order
+ # with two sellers owes each of them their own share.
+ metric :commission, sql: SELLER_COMMISSION_SUBQUERY, base: :line_items, format: :money,
+ subject: -> { Spree::CommissionLine }, key_scope: 'read_commissions'
+ # What the sellers are owed on these sales: the goods they sold, less
+ # the marketplace's cut and anything the buyer sent back.
+ metric :seller_payout,
+ sql: "SUM(%{line_items}.pre_tax_amount) - #{LINE_ITEM_REFUNDS_SUBQUERY} - #{SELLER_COMMISSION_SUBQUERY}",
+ base: :line_items, format: :money,
+ subject: -> { Spree::SellerTransfer }, key_scope: 'read_payouts'
dimension :completed_at, base: :orders, column: :completed_at, type: :time, grains: %i[day week month]
dimension :payment_status, base: :orders, column: :payment_status,
@@ -55,6 +148,24 @@ module Spree
end
}
+ # First-time or returning, decided per order against the buyer's own
+ # history rather than a stored flag: an order is "returning" when the
+ # same email completed an earlier one. Imported history and canceled
+ # orders therefore stay correct without a backfill.
+ dimension :customer_type, base: :orders, expression: CUSTOMER_TYPE_SQL,
+ values: -> { %w[first_time returning] }
+
+ # The seller who sold the line. Marketplace stores group by this;
+ # single-seller stores get one row, which is honest.
+ dimension :seller, base: :line_items, column: :seller_id, 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: { slug: seller.slug } }]
+ end
+ }
+
# Keyed by the order's email (guests have no customer row); a
# prefixed customer id in a filter resolves to that customer's email.
dimension :customer, base: :orders, column: :email, lookup: :customer,
diff --git a/spree/core/lib/spree/reporting/query.rb b/spree/core/lib/spree/reporting/query.rb
index 6b277ce1d9..d86a0a4fa2 100644
--- a/spree/core/lib/spree/reporting/query.rb
+++ b/spree/core/lib/spree/reporting/query.rb
@@ -73,7 +73,7 @@ module Spree
# consumer — API controller, saved reports, agent tools — must ensure
# `:read` on each before executing.
def required_subjects
- ([Spree::Order] + referenced_dimensions.filter_map(&:subject).map(&:call)).uniq
+ ([Spree::Order] + authorized_members.filter_map(&:subject).map(&:call)).uniq
end
# The subjects a given ability may not read — empty when the query is
@@ -90,7 +90,16 @@ module Spree
# endpoint and covers the order-data floor): the `key_scope` of every
# referenced member with an authorization subject.
def required_key_scopes
- referenced_dimensions.filter_map(&:key_scope).uniq
+ authorized_members.filter_map(&:key_scope).uniq
+ end
+
+ # Every member whose definition names an authorization subject: the
+ # dimensions the query groups or filters by, and the metrics that expose
+ # money living outside the order itself.
+ # Aggregated rather than requested metrics, so a ratio built on a gated
+ # component is gated too.
+ def authorized_members
+ referenced_dimensions + aggregated_metrics
end
def referenced_dimensions
diff --git a/spree/core/lib/spree/reporting/registry.rb b/spree/core/lib/spree/reporting/registry.rb
index 812e05be21..4535b1b369 100644
--- a/spree/core/lib/spree/reporting/registry.rb
+++ b/spree/core/lib/spree/reporting/registry.rb
@@ -7,11 +7,19 @@ module Spree
# @!attribute base
# Root relation the aggregate runs against (:orders or :line_items).
# @!attribute format
- # :money | :integer | :decimal — :money metrics force a single-currency scope.
+ # :money | :integer | :decimal | :percent — :money metrics force a
+ # single-currency scope; :percent metrics arrive as the number a merchant
+ # reads (42.5), not the fraction.
# @!attribute ratio
# Derived metrics: [numerator_metric, denominator_metric], computed
# post-aggregation per row and for totals.
- Metric = Struct.new(:name, :sql, :base, :format, :ratio, keyword_init: true) do
+ # @!attribute subject
+ # Callable returning the model class a caller must be able to read for
+ # this number — for a metric that exposes money outside the order itself,
+ # like the marketplace's commission. Declared with key_scope.
+ # @!attribute key_scope
+ # API-key scope the same number requires.
+ Metric = Struct.new(:name, :sql, :base, :format, :ratio, :subject, :key_scope, keyword_init: true) do
def derived? = ratio.present?
def money? = format == :money
end
@@ -51,10 +59,16 @@ module Spree
# Enumerable raw values for status-like dimensions (an Array, or a lambda
# returning one so model constants load lazily). Published in the schema
# as the filter value list.
- Dimension = Struct.new(:name, :base, :column, :joins, :type, :grains, :lookup,
+ Dimension = Struct.new(:name, :base, :column, :expression, :joins, :type, :grains, :lookup,
:resolve, :hydrate, :subject, :key_scope, :values, keyword_init: true) do
def time? = type == :time
+ # A dimension whose key is computed rather than read from a column. The
+ # compiler validates `column` down to `table.column` so registration
+ # cannot smuggle SQL by accident; `expression` is how a developer says
+ # the SQL is deliberate, and it carries the same trust as a metric's.
+ def expression? = expression.present?
+
def enumerated_values
values.respond_to?(:call) ? values.call : values
end
@@ -74,6 +88,9 @@ module Spree
def metric(name, replace: false, **opts)
name = name.to_sym
raise ArgumentError, "metric #{name} already registered (pass replace: true to override)" if @metrics.key?(name) && !replace
+ if opts[:subject] && opts[:key_scope].blank?
+ raise ArgumentError, "metric #{name} declares a subject and must also declare its key_scope"
+ end
opts[:format] ||= :integer
@metrics[name] = Metric.new(name: name, **opts)
@@ -86,6 +103,10 @@ module Spree
raise ArgumentError, "dimension #{name} declares a subject and must also declare its key_scope"
end
+ if opts[:column].blank? && opts[:expression].blank?
+ raise ArgumentError, "dimension #{name} needs a column or an expression"
+ end
+
opts[:type] ||= :value
@dimensions[name] = Dimension.new(name: name, **opts)
end
diff --git a/spree/core/lib/spree/reporting/schema.rb b/spree/core/lib/spree/reporting/schema.rb
index b7460f5283..28a9bc2a70 100644
--- a/spree/core/lib/spree/reporting/schema.rb
+++ b/spree/core/lib/spree/reporting/schema.rb
@@ -9,14 +9,16 @@ module Spree
class Schema
# @param store [Spree::Store]
# @param registry [Registry]
- # @param allowed [Proc] ->(Dimension) { true/false } — permission gate
- def initialize(store:, registry: Spree.reporting, allowed: ->(_dimension) { true })
+ # @param allowed [Proc] ->(member) { true/false } — permission gate,
+ # asked about metrics and dimensions alike
+ def initialize(store:, registry: Spree.reporting, allowed: ->(_member) { true })
@store = store
@registry = registry
@allowed = allowed
end
def to_h
+ metrics = @registry.metrics.values.select { |m| @allowed.call(m) }
dimensions = @registry.dimensions.values.select { |d| @allowed.call(d) }
{
meta: {
@@ -24,8 +26,8 @@ module Spree
timezone: (Time.find_zone(@store.preferred_timezone) || Time.zone).name,
supported_currencies: @store.supported_currencies_list.map(&:iso_code)
},
- metrics: @registry.metrics.values.map { |m| metric_entry(m) },
- dimensions: dimensions.map { |d| dimension_entry(d) },
+ metrics: metrics.map { |m| metric_entry(m) },
+ dimensions: dimensions.map { |d| dimension_entry(d, metrics) },
time_range: {
presets: (Query::PRESETS + Query::RELATIVE_PRESETS).map { |p| { name: p, label: translate('presets', p, :label) } },
relative: %w[last_<n>_days last_<n>_weeks last_<n>_months],
@@ -56,7 +58,7 @@ module Spree
}.compact
end
- def dimension_entry(dimension)
+ def dimension_entry(dimension, metrics)
{
name: dimension.name,
label: translate('dimensions', dimension.name, :label),
@@ -68,7 +70,7 @@ module Spree
values: dimension.enumerated_values&.map { |value| { name: value, label: self.class.value_label(dimension, value) } },
# Order-level metrics cannot be broken down by line-item dimensions
# (they would double count) — the compiler enforces the same rule.
- compatible_metrics: @registry.metrics.values.select { |m| @registry.compatible?(m, dimension) }.map(&:name)
+ compatible_metrics: metrics.select { |m| @registry.compatible?(m, dimension) }.map(&:name)
}.compact
end
diff --git a/spree/core/lib/spree/testing_support/factories/saved_report_factory.rb b/spree/core/lib/spree/testing_support/factories/saved_report_factory.rb
index 8c28129a06..8301cce485 100644
--- a/spree/core/lib/spree/testing_support/factories/saved_report_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/saved_report_factory.rb
@@ -2,6 +2,6 @@ FactoryBot.define do
factory :saved_report, class: Spree::SavedReport do
store { Spree::Store.default }
sequence(:name) { |n| "Report #{n}" }
- query { { 'metrics' => %w[gross_revenue orders_count], 'dimensions' => %w[channel] } }
+ query { { 'metrics' => %w[total_sales orders], 'dimensions' => %w[channel] } }
end
end
diff --git a/spree/core/spec/lib/spree/reporting/query_spec.rb b/spree/core/spec/lib/spree/reporting/query_spec.rb
index 18779dcfe6..2b4d0d66a6 100644
--- a/spree/core/spec/lib/spree/reporting/query_spec.rb
+++ b/spree/core/spec/lib/spree/reporting/query_spec.rb
@@ -9,11 +9,11 @@ RSpec.describe Spree::Reporting::Query do
describe 'validation' do
it 'rejects unknown metrics naming the valid ones' do
- expect { run(metrics: %w[nope]) }.to raise_error(Spree::Reporting::UnknownMember, /net_revenue/)
+ expect { run(metrics: %w[nope]) }.to raise_error(Spree::Reporting::UnknownMember, /net_sales/)
end
it 'rejects unknown dimensions' do
- expect { run(metrics: %w[orders_count], dimensions: %w[nope]) }.to raise_error(Spree::Reporting::UnknownMember)
+ expect { run(metrics: %w[orders], dimensions: %w[nope]) }.to raise_error(Spree::Reporting::UnknownMember)
end
it 'rejects empty metrics' do
@@ -21,28 +21,28 @@ RSpec.describe Spree::Reporting::Query do
end
it 'rejects invalid grains' do
- expect { run(metrics: %w[orders_count], dimensions: [{ name: 'completed_at', grain: 'decade' }]) }
+ expect { run(metrics: %w[orders], dimensions: [{ name: 'completed_at', grain: 'decade' }]) }
.to raise_error(Spree::Reporting::InvalidQuery, /grain/)
end
it 'rejects invalid filter ops' do
- expect { run(metrics: %w[orders_count], filters: [{ dimension: 'channel', op: 'matches', value: 'x' }]) }
+ expect { run(metrics: %w[orders], filters: [{ dimension: 'channel', op: 'matches', value: 'x' }]) }
.to raise_error(Spree::Reporting::InvalidQuery, /op/)
end
it 'rejects order-based metrics grouped by line-item dimensions' do
- expect { run(metrics: %w[gross_revenue], dimensions: %w[category]) }
+ expect { run(metrics: %w[total_sales], dimensions: %w[category]) }
.to raise_error(Spree::Reporting::InvalidQuery, /cannot be grouped/)
end
it 'rejects sorting by a metric that was not requested' do
- expect { run(metrics: %w[orders_count], dimensions: %w[customer], sort: '-net_revenue') }
+ expect { run(metrics: %w[orders], dimensions: %w[customer], sort: '-net_sales') }
.to raise_error(Spree::Reporting::InvalidQuery, /sort/)
end
it 'raises on a channel filter from another store' do
foreign_channel = create(:channel, store: create(:store))
- expect { run(metrics: %w[orders_count], filters: [{ dimension: 'channel', op: 'eq', value: foreign_channel.prefixed_id }]) }
+ expect { run(metrics: %w[orders], filters: [{ dimension: 'channel', op: 'eq', value: foreign_channel.prefixed_id }]) }
.to raise_error(ActiveRecord::RecordNotFound)
end
end
@@ -50,34 +50,34 @@ RSpec.describe Spree::Reporting::Query do
describe 'contract shape' do
it 'rejects malformed shapes as invalid queries, never as server errors' do
expect { run(metrics: { a: 'b' }) }.to raise_error(Spree::Reporting::InvalidQuery)
- expect { run(metrics: %w[orders_count], dimensions: [{ grain: 'day' }]) }.to raise_error(Spree::Reporting::InvalidQuery)
- expect { run(metrics: %w[orders_count], filters: %w[channel]) }.to raise_error(Spree::Reporting::InvalidQuery)
- expect { run(metrics: %w[orders_count], time_range: 'last_month') }.to raise_error(Spree::Reporting::InvalidQuery)
+ expect { run(metrics: %w[orders], dimensions: [{ grain: 'day' }]) }.to raise_error(Spree::Reporting::InvalidQuery)
+ expect { run(metrics: %w[orders], filters: %w[channel]) }.to raise_error(Spree::Reporting::InvalidQuery)
+ expect { run(metrics: %w[orders], time_range: 'last_month') }.to raise_error(Spree::Reporting::InvalidQuery)
end
it 'refuses a limit that is not a positive integer' do
- expect { run(metrics: %w[orders_count], dimensions: %w[channel], limit: 'abc') }
+ expect { run(metrics: %w[orders], dimensions: %w[channel], limit: 'abc') }
.to raise_error(Spree::Reporting::InvalidQuery, /limit/)
- expect { run(metrics: %w[orders_count], dimensions: %w[channel], limit: 0) }
+ expect { run(metrics: %w[orders], dimensions: %w[channel], limit: 0) }
.to raise_error(Spree::Reporting::InvalidQuery, /limit/)
end
it 'refuses partial times instead of filling in today' do
- expect { run(metrics: %w[orders_count], time_range: { since: '09:00' }) }
+ expect { run(metrics: %w[orders], time_range: { since: '09:00' }) }
.to raise_error(Spree::Reporting::InvalidQuery, /ISO 8601/)
end
it 'widens a date-only until to the end of that day' do
create(:completed_order_with_totals, store: store, completed_at: 1.hour.ago)
- result = run(metrics: %w[orders_count], time_range: { since: 2.days.ago.to_date.to_s, until: Date.current.to_s })
- expect(result.totals[:orders_count][:value]).to eq(1)
+ result = run(metrics: %w[orders], time_range: { since: 2.days.ago.to_date.to_s, until: Date.current.to_s })
+ expect(result.totals[:orders][:value]).to eq(1)
end
end
describe '#previous_time_range' do
it 'keeps midnight edges across a DST change by shifting whole days' do
allow(store).to receive(:preferred_timezone).and_return('Europe/Warsaw')
- query = described_class.new(store: store, params: { metrics: %w[orders_count], time_range: { since: '2026-03-20', until: '2026-04-02' } })
+ query = described_class.new(store: store, params: { metrics: %w[orders], time_range: { since: '2026-03-20', until: '2026-04-02' } })
previous = query.previous_time_range
expect(previous.first.in_time_zone('Europe/Warsaw').strftime('%F %T')).to eq('2026-03-06 00:00:00')
@@ -87,19 +87,19 @@ RSpec.describe Spree::Reporting::Query do
describe 'time presets' do
it 'resolves named presets in the store timezone' do
- query = described_class.new(store: store, params: { metrics: %w[orders_count], time_range: { preset: 'yesterday' } })
+ query = described_class.new(store: store, params: { metrics: %w[orders], time_range: { preset: 'yesterday' } })
expect(query.time_range.first).to eq(1.day.ago.in_time_zone(query.time_zone).beginning_of_day)
expect(query.time_range.last).to eq(1.day.ago.in_time_zone(query.time_zone).end_of_day)
- query = described_class.new(store: store, params: { metrics: %w[orders_count], time_range: { preset: 'last_month' } })
+ query = described_class.new(store: store, params: { metrics: %w[orders], time_range: { preset: 'last_month' } })
expect(query.time_range.first).to eq(1.month.ago.in_time_zone(query.time_zone).beginning_of_month)
- query = described_class.new(store: store, params: { metrics: %w[orders_count], time_range: { preset: 'last_4_weeks' } })
+ query = described_class.new(store: store, params: { metrics: %w[orders], time_range: { preset: 'last_4_weeks' } })
expect(query.time_range.first.to_date).to eq(4.weeks.ago.in_time_zone(query.time_zone).to_date)
end
it 'rejects unknown presets naming the valid ones' do
- expect { described_class.new(store: store, params: { metrics: %w[orders_count], time_range: { preset: 'fortnight' } }) }
+ expect { described_class.new(store: store, params: { metrics: %w[orders], time_range: { preset: 'fortnight' } }) }
.to raise_error(Spree::Reporting::InvalidQuery, /last_month/)
end
end
@@ -108,13 +108,13 @@ RSpec.describe Spree::Reporting::Query do
let!(:order) { create(:completed_order_with_totals, store: store, completed_at: 3.days.ago) }
it 'buckets by ISO week start and zero-fills the range' do
- result = run(metrics: %w[orders_count], dimensions: [{ name: 'completed_at', grain: 'week' }],
+ result = run(metrics: %w[orders], dimensions: [{ name: 'completed_at', grain: 'week' }],
time_range: { since: 3.weeks.ago.to_date.to_s, until: Time.current.to_date.to_s })
buckets = result.rows.map { |row| row[:dimensions][:completed_at] }
expect(buckets).to all(satisfy { |b| Date.parse(b).monday? })
expect(buckets.length).to be_between(4, 5)
- expect(result.rows.sum { |row| row[:metrics][:orders_count][:value] }).to eq(1)
+ expect(result.rows.sum { |row| row[:metrics][:orders][:value] }).to eq(1)
end
end
@@ -122,7 +122,7 @@ RSpec.describe Spree::Reporting::Query do
let!(:order) { create(:completed_order_with_totals, store: store, completed_at: 3.days.ago) }
it 'groups by shipping country from the line-items base too' do
- by_orders = run(metrics: %w[orders_count], dimensions: %w[country])
+ by_orders = run(metrics: %w[orders], dimensions: %w[country])
by_items = run(metrics: %w[units_sold], dimensions: %w[country])
code = order.ship_address.country_code
@@ -131,9 +131,9 @@ RSpec.describe Spree::Reporting::Query do
end
it 'exposes money breakdown metrics' do
- result = run(metrics: %w[discounts_total delivery_total tax_total])
- expect(result.totals[:delivery_total][:value]).to eq(order.delivery_total.to_f.round(2))
- expect(result.totals.keys).to contain_exactly(:discounts_total, :delivery_total, :tax_total)
+ result = run(metrics: %w[discounts shipping taxes])
+ expect(result.totals[:shipping][:value]).to eq(order.delivery_total.to_f.round(2))
+ expect(result.totals.keys).to contain_exactly(:discounts, :shipping, :taxes)
end
it 'ranks variants' do
@@ -142,18 +142,94 @@ RSpec.describe Spree::Reporting::Query do
end
end
+ describe 'the sales chain' do
+ let!(:order) { create(:completed_order_with_totals, store: store, completed_at: 3.days.ago) }
+
+ it 'derives gross sales from the line prices before discounts' do
+ line = order.line_items.first
+ result = run(metrics: %w[gross_sales])
+ expect(result.totals[:gross_sales][:value]).to eq((line.price * line.quantity).to_f.round(2))
+ end
+
+ it 'nets refunds out of returns, net sales and total sales' do
+ before_refund = run(metrics: %w[net_sales total_sales returns])
+ expect(before_refund.totals[:returns][:value]).to eq(0.0)
+
+ create(:refund, amount: 5, payment: create(:payment, order: order, amount: order.total), order: order)
+
+ after_refund = run(metrics: %w[net_sales total_sales returns])
+ expect(after_refund.totals[:returns][:value]).to eq(5.0)
+ expect(after_refund.totals[:total_sales][:value]).to eq(before_refund.totals[:total_sales][:value] - 5)
+ expect(after_refund.totals[:net_sales][:value]).to be < before_refund.totals[:net_sales][:value]
+ end
+
+ it 'counts an order once however many refunds it carries' do
+ payment = create(:payment, order: order, amount: order.total)
+ 2.times { create(:refund, amount: 4, payment: payment, order: order) }
+
+ result = run(metrics: %w[returns orders])
+ expect(result.totals[:returns][:value]).to eq(8.0)
+ expect(result.totals[:orders][:value]).to eq(1)
+ end
+
+ it 'treats an uncosted variant as zero cost and reports margin as a percentage' do
+ order.line_items.first.update_columns(cost_price: nil)
+ result = run(metrics: %w[cost_of_goods gross_profit gross_margin net_sales])
+
+ expect(result.totals[:cost_of_goods][:value]).to eq(0.0)
+ expect(result.totals[:gross_profit][:value]).to eq(result.totals[:net_sales][:value])
+ expect(result.totals[:gross_margin][:value]).to eq(100.0)
+ end
+ end
+
+ describe 'customer type' do
+ let(:customer) { create(:user) }
+ let!(:first) { create(:completed_order_with_totals, store: store, customer: customer, completed_at: 10.days.ago) }
+ let!(:second) { create(:completed_order_with_totals, store: store, customer: customer, completed_at: 3.days.ago) }
+
+ it 'calls an order returning when the same buyer completed an earlier one' do
+ result = run(metrics: %w[orders], dimensions: %w[customer_type],
+ time_range: { since: 20.days.ago.to_date.to_s, until: Date.current.to_s })
+
+ counts = result.rows.to_h { |row| [row[:dimensions][:customer_type], row[:metrics][:orders][:value]] }
+ expect(counts['first_time']).to eq(1)
+ expect(counts['returning']).to eq(1)
+ end
+ end
+
+ describe 'seller payout' do
+ let!(:seller) { create(:seller, :approved, store: store) }
+ let!(:order) { create(:completed_order_with_totals, store: store, completed_at: 3.days.ago) }
+ let(:line_item) { order.line_items.first }
+
+ before do
+ line_item.update_columns(seller_id: seller.id)
+ create(:commission_line, order: order, line_item: line_item, seller: seller,
+ amount: 2, total: 2, currency: order.currency)
+ end
+
+ it 'pays the seller what is left of their lines after the commission' do
+ result = run(metrics: %w[net_sales commission seller_payout], dimensions: %w[seller])
+
+ row = result.rows.first
+ expect(row[:dimensions][:seller]).to eq(seller.id)
+ expect(row[:metrics][:commission][:value]).to eq(2.0)
+ expect(row[:metrics][:seller_payout][:value]).to eq(row[:metrics][:net_sales][:value] - 2)
+ end
+ end
+
describe 'joins that are not one-to-one' do
let!(:order) { create(:completed_order_with_totals, store: store, completed_at: 3.days.ago) }
let(:product) { order.line_items.first.variant.product }
let!(:categories) { create_list(:category, 2).each { |category| product.categories << category } }
it 'keeps the totals on the base rows while grouping still fans out per category' do
- result = run(metrics: %w[net_revenue units_sold], dimensions: %w[category])
- ungrouped = run(metrics: %w[net_revenue units_sold])
+ result = run(metrics: %w[net_sales units_sold], dimensions: %w[category])
+ ungrouped = run(metrics: %w[net_sales units_sold])
expect(result.rows.length).to eq(2)
expect(result.totals[:units_sold][:value]).to eq(ungrouped.totals[:units_sold][:value])
- expect(result.totals[:net_revenue][:value]).to eq(ungrouped.totals[:net_revenue][:value])
+ expect(result.totals[:net_sales][:value]).to eq(ungrouped.totals[:net_sales][:value])
end
it 'counts a line item once when a filter matches it through several categories' do
@@ -168,56 +244,66 @@ RSpec.describe Spree::Reporting::Query do
it 'resolves a prefixed customer id to the order email key' do
customer = order.customer
- result = run(metrics: %w[orders_count], filters: [{ dimension: 'customer', op: 'eq', value: customer.prefixed_id }])
- expect(result.totals[:orders_count][:value]).to eq(1)
+ result = run(metrics: %w[orders], filters: [{ dimension: 'customer', op: 'eq', value: customer.prefixed_id }])
+ expect(result.totals[:orders][:value]).to eq(1)
end
it 'accepts a customer with no orders in this store as an empty filter' do
stranger = create(:user)
- result = run(metrics: %w[orders_count], filters: [{ dimension: 'customer', op: 'eq', value: stranger.prefixed_id }])
- expect(result.totals[:orders_count][:value]).to eq(0)
+ result = run(metrics: %w[orders], filters: [{ dimension: 'customer', op: 'eq', value: stranger.prefixed_id }])
+ expect(result.totals[:orders][:value]).to eq(0)
end
it 'still accepts a plain email' do
- result = run(metrics: %w[orders_count], filters: [{ dimension: 'customer', op: 'eq', value: order.email }])
- expect(result.totals[:orders_count][:value]).to eq(1)
+ result = run(metrics: %w[orders], filters: [{ dimension: 'customer', op: 'eq', value: order.email }])
+ expect(result.totals[:orders][:value]).to eq(1)
end
end
describe '#required_subjects' do
it 'includes order data plus every referenced member subject' do
- query = described_class.new(store: store, params: { metrics: %w[net_revenue], dimensions: %w[product] })
+ query = described_class.new(store: store, params: { metrics: %w[net_sales], dimensions: %w[product] })
expect(query.required_subjects).to contain_exactly(Spree::Order, Spree::Product)
- query = described_class.new(store: store, params: { metrics: %w[orders_count] })
+ query = described_class.new(store: store, params: { metrics: %w[orders] })
expect(query.required_subjects).to contain_exactly(Spree::Order)
end
+
+ it 'gates a metric that exposes money living outside the order' do
+ query = described_class.new(store: store, params: { metrics: %w[commission seller_payout] })
+ expect(query.required_subjects).to contain_exactly(Spree::Order, Spree::CommissionLine, Spree::SellerTransfer)
+ end
end
describe '#required_key_scopes' do
it 'collects the key scopes of referenced members, including filters' do
query = described_class.new(store: store, params: {
- metrics: %w[net_revenue],
+ metrics: %w[net_sales],
dimensions: %w[product],
filters: [{ dimension: 'category', op: 'eq', value: 'ctg_x' }]
})
expect(query.required_key_scopes).to contain_exactly('read_products', 'read_categories')
- query = described_class.new(store: store, params: { metrics: %w[orders_count], dimensions: %w[channel] })
+ query = described_class.new(store: store, params: { metrics: %w[orders], dimensions: %w[channel] })
expect(query.required_key_scopes).to be_empty
end
+
+ it 'collects the key scope of a gated metric' do
+ query = described_class.new(store: store, params: { metrics: %w[commission] })
+ expect(query.required_key_scopes).to contain_exactly('read_commissions')
+ end
end
describe 'execution' do
context 'with no orders' do
it 'returns zero totals and zero-filled day rows' do
- result = run(metrics: %w[gross_revenue orders_count aov], dimensions: [{ name: 'completed_at', grain: 'day' }])
+ result = run(metrics: %w[total_sales orders average_order_value], dimensions: [{ name: 'completed_at', grain: 'day' }])
- expect(result.totals[:gross_revenue][:value]).to eq(0.0)
- expect(result.totals[:orders_count][:value]).to eq(0)
- expect(result.totals[:aov][:value]).to eq(0.0)
+ expect(result.totals[:total_sales][:value]).to eq(0.0)
+ expect(result.totals[:orders][:value]).to eq(0)
+ expect(result.totals[:average_order_value][:value]).to eq(0.0)
expect(result.rows.length).to eq(31) # default 30 days + today
- expect(result.rows).to all(satisfy { |row| row[:metrics][:orders_count][:value].zero? })
+ expect(result.rows).to all(satisfy { |row| row[:metrics][:orders][:value].zero? })
end
end
@@ -227,43 +313,43 @@ RSpec.describe Spree::Reporting::Query do
let!(:order2) { create(:completed_order_with_totals, store: store, completed_at: 2.days.ago) }
it 'computes whole-period totals' do
- result = run(metrics: %w[gross_revenue orders_count units_sold customers_count aov])
+ result = run(metrics: %w[total_sales orders units_sold customers average_order_value])
expected_gross = (order1.total + order2.total).to_f.round(2)
expected_units = order1.line_items.sum(:quantity) + order2.line_items.sum(:quantity)
- expect(result.totals[:gross_revenue][:value]).to eq(expected_gross)
- expect(result.totals[:orders_count][:value]).to eq(2)
+ expect(result.totals[:total_sales][:value]).to eq(expected_gross)
+ expect(result.totals[:orders][:value]).to eq(2)
expect(result.totals[:units_sold][:value]).to eq(expected_units)
- expect(result.totals[:customers_count][:value]).to eq(2)
- expect(result.totals[:aov][:value]).to eq((expected_gross / 2).round(2))
+ expect(result.totals[:customers][:value]).to eq(2)
+ expect(result.totals[:average_order_value][:value]).to eq((expected_gross / 2).round(2))
end
it 'reports nil growth without a previous-period baseline' do
- result = run(metrics: %w[gross_revenue orders_count], compare: 'previous_period')
+ result = run(metrics: %w[total_sales orders], compare: 'previous_period')
- expect(result.totals[:gross_revenue][:growth]).to be_nil
- expect(result.totals[:orders_count][:growth]).to be_nil
+ expect(result.totals[:total_sales][:growth]).to be_nil
+ expect(result.totals[:orders][:growth]).to be_nil
expect(result.meta[:previous_time_range]).to be_present
end
it 'buckets day rows in order and fills empty days with zeros' do
result = run(
- metrics: %w[gross_revenue orders_count units_sold],
+ metrics: %w[total_sales orders units_sold],
dimensions: [{ name: 'completed_at', grain: 'day' }],
compare: 'previous_period'
)
expect(result.rows.length).to eq(31)
day = result.rows.find { |row| row[:dimensions][:completed_at] == 5.days.ago.to_date.to_s }
- expect(day[:metrics][:orders_count][:value]).to eq(1)
- expect(day[:metrics][:gross_revenue][:value]).to eq(order1.total.to_f.round(2))
+ expect(day[:metrics][:orders][:value]).to eq(1)
+ expect(day[:metrics][:total_sales][:value]).to eq(order1.total.to_f.round(2))
expect(day[:metrics][:units_sold][:value]).to be > 0
expect(day[:metrics].values).to all(have_key(:previous))
end
it 'respects an explicit time_range' do
- result = run(metrics: %w[orders_count], dimensions: [{ name: 'completed_at', grain: 'day' }],
+ result = run(metrics: %w[orders], dimensions: [{ name: 'completed_at', grain: 'day' }],
time_range: { since: 7.days.ago.to_date.to_s, until: Time.current.to_date.to_s })
expect(result.rows.length).to eq(8)
@@ -273,37 +359,37 @@ RSpec.describe Spree::Reporting::Query do
channel = create(:channel, store: store)
create(:completed_order_with_totals, store: store, channel: channel, completed_at: 3.days.ago)
- result = run(metrics: %w[orders_count], filters: [{ dimension: 'channel', op: 'eq', value: channel.prefixed_id }])
- expect(result.totals[:orders_count][:value]).to eq(1)
+ result = run(metrics: %w[orders], filters: [{ dimension: 'channel', op: 'eq', value: channel.prefixed_id }])
+ expect(result.totals[:orders][:value]).to eq(1)
end
it 'ranks customers by revenue with sort and limit' do
- result = run(metrics: %w[gross_revenue orders_count], dimensions: %w[customer], sort: '-gross_revenue', limit: 1)
+ result = run(metrics: %w[total_sales orders], dimensions: %w[customer], sort: '-total_sales', limit: 1)
expect(result.rows.length).to eq(1)
top_email = result.rows.first[:dimensions][:customer]
top_order = [order1, order2].max_by(&:total)
expect(top_email).to eq(top_order.email)
- expect(result.rows.first[:metrics][:orders_count][:value]).to eq(1)
+ expect(result.rows.first[:metrics][:orders][:value]).to eq(1)
end
it 'ranks products by net revenue with per-row growth' do
- result = run(metrics: %w[net_revenue units_sold], dimensions: %w[product],
- compare: 'previous_period', sort: '-net_revenue', limit: 5)
+ result = run(metrics: %w[net_sales units_sold], dimensions: %w[product],
+ compare: 'previous_period', sort: '-net_sales', limit: 5)
expect(result.rows).to be_present
row = result.rows.first
expect(row[:dimensions][:product]).to be_present
- expect(row[:metrics][:net_revenue][:value]).to be > 0
+ expect(row[:metrics][:net_sales][:value]).to be > 0
expect(row[:metrics][:units_sold][:value]).to be > 0
- expect(row[:metrics][:net_revenue][:growth]).to be_nil # no previous-period sales
+ expect(row[:metrics][:net_sales][:growth]).to be_nil # no previous-period sales
end
it 'ranks categories by net revenue' do
category = create(:category, store: store)
order1.products.each { |product| product.categories << category }
- result = run(metrics: %w[net_revenue units_sold], dimensions: %w[category], sort: '-net_revenue')
+ result = run(metrics: %w[net_sales units_sold], dimensions: %w[category], sort: '-net_sales')
expect(result.rows.length).to eq(1)
expect(result.rows.first[:dimensions][:category]).to eq(category.id)
@@ -311,8 +397,8 @@ RSpec.describe Spree::Reporting::Query do
end
it 'groups by payment status without a lookup' do
- result = run(metrics: %w[orders_count], dimensions: %w[payment_status])
- expect(result.rows.sum { |row| row[:metrics][:orders_count][:value] }).to eq(2)
+ result = run(metrics: %w[orders], dimensions: %w[payment_status])
+ expect(result.rows.sum { |row| row[:metrics][:orders][:value] }).to eq(2)
end
end
@@ -321,29 +407,29 @@ RSpec.describe Spree::Reporting::Query do
let!(:older_order) { create(:completed_order_with_totals, store: store, completed_at: 35.days.ago) }
it 'computes numeric growth against the previous period' do
- result = run(metrics: %w[gross_revenue orders_count], compare: 'previous_period')
+ result = run(metrics: %w[total_sales orders], compare: 'previous_period')
- expect(result.totals[:orders_count][:previous]).to eq(1)
- expect(result.totals[:gross_revenue][:growth]).to be_a(Numeric)
+ expect(result.totals[:orders][:previous]).to eq(1)
+ expect(result.totals[:total_sales][:growth]).to be_a(Numeric)
end
it 'aligns previous buckets when a value dimension sits beside the time dimension' do
# Exactly one range length (31 days) before recent_order — without
# zero-filled buckets only the observed keys can carry a previous value.
create(:completed_order_with_totals, store: store, completed_at: 36.days.ago)
- result = run(metrics: %w[orders_count],
+ result = run(metrics: %w[orders],
dimensions: [{ name: 'completed_at', grain: 'day' }, 'channel'],
compare: 'previous_period')
row = result.rows.find { |r| r[:dimensions][:completed_at] == 5.days.ago.to_date.to_s }
- expect(row[:metrics][:orders_count][:previous]).to eq(1)
+ expect(row[:metrics][:orders][:previous]).to eq(1)
end
it 'aligns previous-period day buckets by range offset' do
- result = run(metrics: %w[orders_count], dimensions: [{ name: 'completed_at', grain: 'day' }],
+ result = run(metrics: %w[orders], dimensions: [{ name: 'completed_at', grain: 'day' }],
compare: 'previous_period')
- aligned = result.rows.find { |row| row[:metrics][:orders_count][:previous].to_i == 1 }
+ aligned = result.rows.find { |row| row[:metrics][:orders][:previous].to_i == 1 }
expect(aligned).to be_present
end
end
@@ -355,9 +441,9 @@ RSpec.describe Spree::Reporting::Query do
before { canceled.update_columns(status: 'canceled') }
it 'counts only what stayed sold on both bases' do
- result = run(metrics: %w[gross_revenue orders_count units_sold])
- expect(result.totals[:orders_count][:value]).to eq(1)
- expect(result.totals[:gross_revenue][:value]).to eq(order.total.to_f.round(2))
+ result = run(metrics: %w[total_sales orders units_sold])
+ expect(result.totals[:orders][:value]).to eq(1)
+ expect(result.totals[:total_sales][:value]).to eq(order.total.to_f.round(2))
expect(result.totals[:units_sold][:value]).to eq(order.line_items.sum(:quantity))
end
end
@@ -370,12 +456,12 @@ RSpec.describe Spree::Reporting::Query do
let!(:previous_order) { create(:completed_order_with_totals, store: store, completed_at: '2026-07-07 12:00'.in_time_zone) }
it 'pairs week buckets by position so no counterpart falls outside the previous period' do
- result = run(metrics: %w[orders_count], dimensions: [{ name: 'completed_at', grain: 'week' }],
+ result = run(metrics: %w[orders], dimensions: [{ name: 'completed_at', grain: 'week' }],
compare: 'previous_period', time_range: { since: '2026-08-05', until: '2026-09-03' })
bucket = result.rows.find { |row| row[:dimensions][:completed_at] == '2026-08-03' }
- expect(bucket[:metrics][:orders_count][:value]).to eq(1)
- expect(bucket[:metrics][:orders_count][:previous]).to eq(1)
+ expect(bucket[:metrics][:orders][:value]).to eq(1)
+ expect(bucket[:metrics][:orders][:previous]).to eq(1)
end
it 'pairs month buckets by position on a rolling range that starts on the 1st' do
@@ -384,13 +470,13 @@ RSpec.describe Spree::Reporting::Query do
create(:completed_order_with_totals, store: store, completed_at: '2026-09-15 12:00'.in_time_zone)
create(:completed_order_with_totals, store: store, completed_at: '2026-08-15 12:00'.in_time_zone)
- result = run(metrics: %w[orders_count], dimensions: [{ name: 'completed_at', grain: 'month' }],
+ result = run(metrics: %w[orders], dimensions: [{ name: 'completed_at', grain: 'month' }],
compare: 'previous_period', time_range: { since: '2026-09-01', until: '2026-10-01' })
august_orders = store.orders.complete.where(completed_at: '2026-08-01'.in_time_zone..'2026-08-31'.in_time_zone.end_of_day).count
september = result.rows.find { |row| row[:dimensions][:completed_at] == '2026-09-01' }
- expect(september[:metrics][:orders_count][:value]).to eq(1)
- expect(september[:metrics][:orders_count][:previous]).to eq(august_orders)
+ expect(september[:metrics][:orders][:value]).to eq(1)
+ expect(september[:metrics][:orders][:previous]).to eq(august_orders)
expect(august_orders).to be_positive
end
end
@@ -404,15 +490,15 @@ RSpec.describe Spree::Reporting::Query do
let!(:previous_order) { create(:completed_order_with_totals, store: store, completed_at: '2026-07-07 12:00'.in_time_zone) }
it 'pairs from the start and leaves the trailing bucket unpaired' do
- result = run(metrics: %w[orders_count], dimensions: [{ name: 'completed_at', grain: 'week' }],
+ result = run(metrics: %w[orders], dimensions: [{ name: 'completed_at', grain: 'week' }],
compare: 'previous_period', time_range: { since: '2026-08-02', until: '2026-08-31' })
paired = result.rows.find { |row| row[:dimensions][:completed_at] == '2026-08-03' }
- expect(paired[:metrics][:orders_count][:value]).to eq(1)
- expect(paired[:metrics][:orders_count][:previous]).to eq(1)
+ expect(paired[:metrics][:orders][:value]).to eq(1)
+ expect(paired[:metrics][:orders][:previous]).to eq(1)
trailing = result.rows.find { |row| row[:dimensions][:completed_at] == '2026-08-31' }
- expect(trailing[:metrics][:orders_count][:previous]).to eq(0)
+ expect(trailing[:metrics][:orders][:previous]).to eq(0)
end
end
@@ -426,12 +512,12 @@ RSpec.describe Spree::Reporting::Query do
let!(:previous_order) { create(:completed_order_with_totals, store: store, completed_at: ((from + 45) << 3).in_time_zone.change(hour: 12)) }
it 'compares each month with the month one period earlier, never a neighbour' do
- result = run(metrics: %w[orders_count], dimensions: [{ name: 'completed_at', grain: 'month' }],
+ result = run(metrics: %w[orders], dimensions: [{ name: 'completed_at', grain: 'month' }],
compare: 'previous_period', time_range: { since: from.to_s, until: Date.current.to_s })
bucket = result.rows.find { |row| row[:dimensions][:completed_at] == (from + 45).beginning_of_month.to_s }
- expect(bucket[:metrics][:orders_count][:value]).to eq(1)
- expect(bucket[:metrics][:orders_count][:previous]).to eq(1)
+ expect(bucket[:metrics][:orders][:value]).to eq(1)
+ expect(bucket[:metrics][:orders][:previous]).to eq(1)
end
end
@@ -440,12 +526,12 @@ RSpec.describe Spree::Reporting::Query do
let!(:previous_order) { create(:completed_order_with_totals, store: store, completed_at: 10.days.ago) }
it 'aligns week buckets by the exact range length snapped to the week start' do
- result = run(metrics: %w[orders_count], dimensions: [{ name: 'completed_at', grain: 'week' }],
+ result = run(metrics: %w[orders], dimensions: [{ name: 'completed_at', grain: 'week' }],
compare: 'previous_period',
time_range: { since: 6.days.ago.to_date.to_s, until: Date.current.to_s })
bucket = result.rows.find { |row| row[:dimensions][:completed_at] == 3.days.ago.to_date.beginning_of_week.to_s }
- expect(bucket[:metrics][:orders_count][:previous]).to eq(1)
+ expect(bucket[:metrics][:orders][:previous]).to eq(1)
end
end
@@ -465,13 +551,13 @@ RSpec.describe Spree::Reporting::Query do
end
it 'never counts other stores or other currencies' do
- result = run(metrics: %w[orders_count gross_revenue])
- expect(result.totals[:orders_count][:value]).to eq(0)
+ result = run(metrics: %w[orders total_sales])
+ expect(result.totals[:orders][:value]).to eq(0)
end
it 'reports the requested currency' do
- result = run(metrics: %w[orders_count], currency: 'EUR')
- expect(result.totals[:orders_count][:value]).to eq(1)
+ result = run(metrics: %w[orders], currency: 'EUR')
+ expect(result.totals[:orders][:value]).to eq(1)
expect(result.meta[:currency]).to eq('EUR')
end
end
diff --git a/spree/core/spec/lib/spree/reporting/registry_spec.rb b/spree/core/spec/lib/spree/reporting/registry_spec.rb
index 1e33e01e70..e537439780 100644
--- a/spree/core/spec/lib/spree/reporting/registry_spec.rb
+++ b/spree/core/spec/lib/spree/reporting/registry_spec.rb
@@ -43,8 +43,8 @@ RSpec.describe Spree::Reporting::Registry do
describe 'core starter vocabulary' do
it 'is registered on Spree.reporting' do
- expect(Spree.reporting.metric!(:net_revenue).base).to eq(:line_items)
- expect(Spree.reporting.metric!(:aov).derived?).to be true
+ expect(Spree.reporting.metric!(:net_sales).base).to eq(:line_items)
+ expect(Spree.reporting.metric!(:average_order_value).derived?).to be true
expect(Spree.reporting.dimension!(:completed_at).grains).to include(:day)
expect(Spree.reporting.dimension!(:product).lookup).to eq(:product)
end
diff --git a/spree/core/spec/lib/spree/reporting/schema_spec.rb b/spree/core/spec/lib/spree/reporting/schema_spec.rb
index 72abaa1779..c40b2ef1e1 100644
--- a/spree/core/spec/lib/spree/reporting/schema_spec.rb
+++ b/spree/core/spec/lib/spree/reporting/schema_spec.rb
@@ -6,7 +6,7 @@ RSpec.describe Spree::Reporting::Schema do
subject(:schema) { described_class.new(store: store).to_h }
it 'describes metrics with localized labels, formats and currency' do
- metric = schema[:metrics].find { |m| m[:name] == :gross_revenue }
+ metric = schema[:metrics].find { |m| m[:name] == :total_sales }
expect(metric[:label]).to eq('Total sales')
expect(metric[:description]).to be_present
expect(metric[:format]).to eq(:money)
@@ -15,11 +15,11 @@ RSpec.describe Spree::Reporting::Schema do
it 'publishes compatible metrics, filter ops and enumerated values per dimension' do
category = schema[:dimensions].find { |d| d[:name] == :category }
- expect(category[:compatible_metrics]).to include(:net_revenue, :units_sold)
- expect(category[:compatible_metrics]).not_to include(:gross_revenue, :aov)
+ expect(category[:compatible_metrics]).to include(:net_sales, :units_sold)
+ expect(category[:compatible_metrics]).not_to include(:total_sales, :average_order_value)
channel = schema[:dimensions].find { |d| d[:name] == :channel }
- expect(channel[:compatible_metrics]).to include(:gross_revenue, :aov, :units_sold)
+ expect(channel[:compatible_metrics]).to include(:total_sales, :average_order_value, :units_sold)
expect(channel[:filter_ops]).to eq(%w[eq in])
status = schema[:dimensions].find { |d| d[:name] == :payment_status }
diff --git a/spree/core/spec/models/spree/exports/report_spec.rb b/spree/core/spec/models/spree/exports/report_spec.rb
index 4c6488c411..998947f85e 100644
--- a/spree/core/spec/models/spree/exports/report_spec.rb
+++ b/spree/core/spec/models/spree/exports/report_spec.rb
@@ -3,7 +3,7 @@ require 'spec_helper'
RSpec.describe Spree::Exports::Report, type: :model do
let(:store) { @default_store }
let(:admin) { create(:admin_user) }
- let(:query) { { 'metrics' => %w[gross_revenue orders_count], 'dimensions' => %w[channel] } }
+ let(:query) { { 'metrics' => %w[total_sales orders], 'dimensions' => %w[channel] } }
before { create(:completed_order_with_totals, store: store, completed_at: 3.days.ago) }
@@ -15,7 +15,7 @@ RSpec.describe Spree::Exports::Report, type: :model do
it 'writes a dimensionless report as a single totals row' do
export = described_class.create!(store: store, user: admin,
- search_params: { query: { 'metrics' => %w[gross_revenue orders_count] } })
+ search_params: { query: { 'metrics' => %w[total_sales orders] } })
export.generate_csv
rows = CSV.read(export.send(:export_tmp_file_path))
@@ -40,7 +40,7 @@ RSpec.describe Spree::Exports::Report, type: :model do
viewer = create(:admin_user, :without_admin_role)
create(:role_user, user: viewer, role: create(:role, permissions: %w[read_reports read_orders]))
export = described_class.new(store: store, user: viewer,
- search_params: { query: { 'metrics' => %w[net_revenue], 'dimensions' => %w[product] } })
+ search_params: { query: { 'metrics' => %w[net_sales], 'dimensions' => %w[product] } })
expect(export).not_to be_valid
expect(export.errors.details[:base]).to include(hash_including(error: :forbidden_reporting_member))
diff --git a/spree/core/spec/models/spree/saved_report_spec.rb b/spree/core/spec/models/spree/saved_report_spec.rb
index 7c5c5b182e..9ca4b90774 100644
--- a/spree/core/spec/models/spree/saved_report_spec.rb
+++ b/spree/core/spec/models/spree/saved_report_spec.rb
@@ -5,9 +5,9 @@ RSpec.describe Spree::SavedReport, type: :model do
it 'saves a compilable query' do
report = described_class.new(store: store, name: 'Sales by channel',
- query: { 'metrics' => %w[gross_revenue], 'dimensions' => %w[channel] })
+ query: { 'metrics' => %w[total_sales], 'dimensions' => %w[channel] })
expect(report).to be_valid
- expect(report.reporting_query.metrics.map(&:name)).to eq([:gross_revenue])
+ expect(report.reporting_query.metrics.map(&:name)).to eq([:total_sales])
end
it 'refuses a query the registry cannot compile' do
@@ -16,9 +16,9 @@ RSpec.describe Spree::SavedReport, type: :model do
expect(report.errors.details[:query]).to include(hash_including(error: :invalid_reporting_query))
# The compiler's own sentence is the useful part — it names the members
# that would have worked — so it rides along as the message.
- expect(report.errors[:query].first).to include('net_revenue')
+ expect(report.errors[:query].first).to include('net_sales')
- report = described_class.new(store: store, name: 'Broken', query: { 'metrics' => %w[gross_revenue], 'dimensions' => %w[category] })
+ report = described_class.new(store: store, name: 'Broken', query: { 'metrics' => %w[total_sales], 'dimensions' => %w[category] })
expect(report).not_to be_valid
expect(report.errors[:query].first).to include('cannot be grouped')
end