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.
Reporting: Additional Metrics, Filters and Grains
Status: Implemented — carts family, promotion vocabulary, metric filters, include_empty, hour grain, year-over-year, lifetime metrics and the two refusal messages all ship; seeded classic reports for the new questions are the one deferred item (see Open Questions)
Target: Spree 6.0 (carts family, promotion vocabulary, metric filters, hour grain, year-over-year, lifetime value, refusal messages)
Depends on: 6.0-analytics-semantic-layer.md (the registry, contract and compiler this extends), 6.0-cart-order-split.md (the Spree::Cart table the carts family reads)
Author: Damian + Claude
Last updated: 2026-09-12 (Decisions 11–13: abandonment ignores the reaper's money-safety carve-out, lifetime value is net of refunds, the hour cap refuses and the picker greys out)
Summary
The semantic layer shipped a vocabulary that answers what merchants ask about
completed orders. A pass over the questions merchants actually type found nine
it cannot answer. Seven are genuine gaps in the vocabulary or the contract and
this plan closes them: abandoned carts and cart conversion (a new carts
family), sales by promotion and coupon code (a new promotion dimension
family on spree_discounts), "which products never sold" (metric filters,
a HAVING clause the contract has no concept of), sales by hour (an hour
grain), "versus the same month last year" (a previous_year compare
mode), and customer lifetime value (a lifetime metric whose window is
deliberately not the report's).
The remaining two are not gaps. "Total sales per product" and "revenue and units shipped together" are refused by design — the first would double-count order-level money onto line items, the second would put two different clocks in one table. Both refusals stay; what changes is that the 422 now explains itself and names the metric or the split that answers the question. A merchant hitting a wall should learn the vocabulary from the error, not file a bug.
One question in the original list stays unanswerable and is recorded as such: traffic-based conversion rate needs sessions and referrers that a headless storefront never sends us. Cart-level conversion — of the carts that were started, how many became orders — is computable and ships here; it is a different and narrower number, and the docs must not let the two be confused.
Problem
The vocabulary is anchored on one root: a completed, non-canceled order. That single choice is what makes the shipped reports trustworthy, and it is also what puts these seven questions out of reach.
| Merchant asks | Today | Why it is out of reach |
|---|---|---|
| "Abandoned carts" | No metric | Every sales base filters completed_at in range; a cart has no completed_at and lives in a different table |
| "Cart conversion rate" | No metric | Same — needs the cart as a root, with the order as the optional join |
| "Sales by promotion or coupon code" | No dimension | discounts is money on a line item with no attribution axis |
| "Which products have never sold?" | Impossible | FILTER_OPS = %w[eq in] filters dimensions only; nothing compiles to HAVING |
| "Sales by hour of day" | Grains stop at day | Every time dimension declares grains: %i[day week month]; time_bucket_sql handles exactly those three |
| "Versus the same month last year" | Only previous period | COMPARE_MODES = %w[previous_period], shifted by an equal day count |
| "Customer lifetime value" | No metric | Every base relation hardcodes completed_at: range, so no per-customer all-time aggregate is reachable |
| "Total sales per product" | Refused | Correct — total_sales is order-level money; per line item it double-counts |
| "Revenue and units shipped" | Refused | Correct — sales and inventory are different families on different clocks |
| "Conversion rate" (traffic) | Unavailable | Correct and permanent — no session data reaches Spree |
The last three rows are the design working. The first seven are the vocabulary being smaller than the questions.
Key Decisions (do not deviate without discussion)
1. Carts are a fourth family, not a filter on orders
In 6.0 a cart is its own table (spree_carts), joined to its order by a unique
spree_orders.cart_id. It has no status, no seller_id, and its customer FK
is customer_id, not user_id. It is therefore a new base in a new
:carts family, registered like any other:
base :carts, family: :carts, table: '%{carts}',
time_column: '%{carts}.created_at',
relation: lambda { |store, range, currency|
scope = store.carts.where(Spree::Cart.table_name => { created_at: range })
currency ? scope.where(Spree::Cart.table_name => { currency: currency }) : scope
}
A cart is anchored on created_at, not completed_at: the question is
"of the carts started in this period, how many converted", and anchoring on
completion would silently drop every cart that never converted — the exact
population being measured. This is a different clock from the sales family,
which is precisely why it is a separate family and why the one-family rule
(Decision 14 of the semantic layer plan) refuses to mix the two. A merchant
who wants carts beside revenue runs two queries; the alternative is a table
where one row means "started in March" and the next means "completed in March".
store.carts already exists, so the store-scoped relation needs no new
association.
2. Abandonment is the definition the reaper already uses, and it is a store preference
Spree::Carts::ReapExpiredJob is the codebase's existing answer to "when is a
cart abandoned": an incomplete cart whose updated_at has gone quiet.
Reporting adopts that column — it is indexed on spree_carts — rather than
inventing a second definition of the same word.
The quiet window is a store preference, abandoned_cart_after_hours
(integer, default 24), read through preferred_abandoned_cart_after_hours and
edited under Settings → Store, exactly as low_stock_threshold was settled in
Decision 15 of the semantic layer plan. It is not a request parameter and not a
global. A cart is abandoned when it is incomplete and untouched for longer than
that window; a cart that is merely incomplete and still being worked on is not
abandoned, and a report that counted it would move every time someone was
mid-checkout.
The reaper caps this history and the docs must say so. Abandoned carts are destroyed after 30 days (guest) or 90 days (customer) by default, so an abandoned-cart report over a longer range under-reports — not because the query is wrong, but because the rows are gone. This is a documented property of the metric, not something the metric should paper over.
3. Cart conversion is a cart-level rate, and it is not the conversion rate merchants read about
carts_converted / carts_started, computed over the carts started in the
period. The join is safe to aggregate over because spree_orders.cart_id
carries a unique index — one cart yields at most one order, so no fan-out.
This is emphatically not the storefront conversion rate (sessions →
purchase), which stays unavailable forever because sessions never reach Spree.
The metric is named cart_conversion_rate rather than conversion_rate for
that reason, and its description says what it measures and what it does not. A
merchant comparing it against an analytics tool's number will otherwise
conclude one of the two is broken.
A cart that completes into an order group (a multi-seller basket splitting
into several orders) is one conversion, not three — the same
COALESCE(order_group_id, id) checkout identity that Promotion#credits_count
already uses.
4. Promotion attribution reads spree_discounts, not the join table
spree_discounts carries promotion_id, promotion_action_id and a
snapshot of the redeemed code on every money row, all indexed. So "sales
by promotion" and "sales by coupon code" are a plain GROUP BY on the money
itself — no walk through spree_order_promotions, which carries no amount and
would need a correlated subquery to produce one.
Three consequences the implementation must respect:
amountis non-positive (enforced by a DB check constraint). Every discount metric sums-amount, so a merchant reads "£4,210 discounted", not "−£4,210".promotion_idis nullified, never cascaded, on promotion deletion. The dimension must therefore tolerate NULL and group it as "Unassigned" — which the LEFT-join rule (Decision 13 of the semantic layer plan) already guarantees. The row keeps itscodeandlabel, so a deleted promotion's discounts stay attributable by code.- The owner is
order_idXORcart_id. Sales-family promotion reporting filters to the order side explicitly; cart-owned rows belong to the carts family. A join that forgets this silently mixes a discount that was never purchased into revenue.
Promotion redemptions are counted in checkouts, not orders, for the same
reason Promotion#credits_count does: a multi-seller basket becomes several
orders, and counting those separately would report one customer's single
redemption as three.
5. Metric filters are a separate contract key, never mixed into filters
Filtering on a metric is a HAVING clause and behaves differently from a
WHERE on a dimension — it runs after aggregation, it cannot use the
id-subquery path, and it interacts with limit. Conflating the two in one
filters array would hide that difference behind identical-looking JSON.
{ "metrics": ["units_sold", "net_sales"],
"dimensions": ["product"],
"metric_filters": [{ "metric": "units_sold", "op": "eq", "value": 0 }],
"time_range": { "preset": "last_quarter" } }
METRIC_FILTER_OPS = %w[eq gt gte lt lte]. A metric filter may only name a
metric the query already requests — the same rule sort follows — so the
number a merchant filters on is a number they can see.
Derived metrics are refused, naming the ingredient to filter instead:
average_order_value is computed in Ruby after aggregation (its ratio never
reaches SQL), so a HAVING on it cannot compile. This matches the existing
rule that a derived metric cannot be SQL-sorted.
6. "Never sold" needs the zero rows, so it is a left join from the dimension
A HAVING units_sold = 0 over the line-items base finds nothing: a product
that never sold has no line item, so it is not in the result set to be
filtered. The natural question needs the dimension's population as the root.
This ships as an explicit include_empty: true on the dimension entry, which
compiles the dimension's lookup relation as the left side and the aggregate as
the right:
{ "metrics": ["units_sold"],
"dimensions": [{ "name": "product", "include_empty": true }],
"metric_filters": [{ "metric": "units_sold", "op": "eq", "value": 0 }] }
It is opt-in and only valid for dimensions with a lookup (a relation exists
to enumerate), because the alternative — making every breakdown include its
empty members — would put every unsold product in every product report.
COALESCE(aggregate, 0) supplies the zero so the filter compares a number
rather than NULL.
7. Hour grain resolves in the store timezone, like every other grain
hour joins %i[day week month] on the time dimensions and gets its three
adapter branches in time_bucket_sql. The store-timezone rule (Decision 7 of
the semantic layer plan) matters more here than anywhere else: "sales by hour
of day" is a question about the merchant's trading day, and reading it in UTC
shifts every peak by the store's offset — the difference between "we sell at
lunchtime" and "we sell mid-morning".
Hour is the one grain where the range genuinely needs a guard: a year at hourly
grain is 8,760 buckets. MAX_BUCKETS (2,000) is checked when the grain is
resolved and refused with a message naming the range and a coarser grain,
rather than being silently truncated.
8. Year-over-year shifts by calendar, not by day count
COMPARE_MODES gains previous_year. The existing previous_period shifts by
an equal number of days, which is right for an arbitrary range and wrong for
this one: "the same month last year" means February to February, and a
day-count shift off a 28-day February lands in January.
previous_year therefore shifts the range by one calendar year in the store's
timezone, and February 29 maps to February 28 in a non-leap year. Bucket
alignment stays positional, as previous_period already does — the first
bucket of this year's range pairs with the first of last year's — so a
year-over-year day series does not misalign on the leap day.
9. Lifetime value is lifetime; the range selects the customers
An LTV that only counted orders inside the report's range would be net_sales
per customer wearing a misleading name. So customer_lifetime_value breaks the
rule every other metric follows, deliberately and in exactly one way: the
time range selects which customers appear in the report; their value covers
their whole history.
A merchant running "top customers by lifetime value, last 30 days" gets the customers who ordered in the last 30 days, ranked by what they have spent ever — which is the question. The metric's description says this outright, because a number that ignores the date picker must explain itself where it is read, not only in the docs.
It compiles as a correlated subquery over the customer's completed,
non-canceled orders — the pattern Decision 14 of the semantic layer plan
already set for order-level money living on another table. It is only valid
grouped by customer (or filtered to one); ungrouped it would sum every
customer's lifetime into a figure that means nothing, so an ungrouped request
is refused with that reason. orders_lifetime ships beside it, since "spent a
lot across many small orders" and "spent a lot once" are different customers.
10. The two refusals stay; the errors start teaching
Neither refusal is relaxed. Both messages are rewritten to name the reason and the way through, because the current wording states a rule without a remedy:
| Query | Today | New |
|---|---|---|
total_sales by product |
"metrics total_sales cannot be grouped by product" | "total_sales is order-level money (it includes shipping, duties and tax that belong to the whole order), so it cannot be split per product without counting the same money under several products. Use net_sales for per-product revenue." |
net_sales + units_shipped |
"metrics from different families cannot be combined in one query: inventory, sales" | "net_sales measures sales (anchored on when the order completed) and units_shipped measures inventory (anchored on when stock moved). One query cannot report both. Run them as two queries." |
This is the Decision 4 principle — reject, never silently narrow — carried through to the wording: the rejection should leave the caller knowing what to send instead. It matters twice over for the agent surface, where the error is the only teacher the model has.
11. Abandonment does not inherit the reaper's money-safety carve-out (2026-09-12)
ReapExpiredJob never destroys a cart carrying a live payment session or a
valid payment. That exclusion exists so the reaper cannot delete rows with
money attached — it is a deletion-safety rule, not a definition of
abandonment. Reporting does not inherit it.
A cart that stalled mid-payment is abandoned by any merchant's reading, and it is the most recoverable kind there is: there is money on the table and a known customer to chase. Excluding it would drop precisely the rows an abandoned-cart report exists to surface.
So the predicate stays the simple one — incomplete, and untouched for longer than the store's window — and the report and the reaper legitimately disagree about which carts they mean. That divergence is recorded here because the two otherwise look like they should match.
12. Lifetime value is net of refunds (2026-09-12)
customer_lifetime_value subtracts refunds, consistent with net_sales and
with the question being asked: a customer who bought heavily and returned most
of it is not a high-value customer, and a gross figure would rank them as one.
The cost is the Decision 14 reversal rule — a refund restates the figure after the fact, so a customer's lifetime value can fall. That is correct and the metric's description says so.
13. The hour cap refuses, and the picker prevents it (2026-09-12)
A range too wide for hourly buckets is a 422 naming the range and a coarser grain, never a silently coarsened result — Decision 4 of the semantic layer plan applies unchanged.
An error the UI lets a merchant walk into is still a UI failure, so the two ship together: the backend refuses, and the builder disables the hour grain for ranges it cannot serve. The backend guard is the correctness boundary; the picker is what stops anyone meeting it.
Design Details
New registry members
Carts family — one base, five metrics, three dimensions:
| Member | Kind | Definition |
|---|---|---|
carts_started |
metric | COUNT(*) over the base |
carts_converted |
metric | COUNT(DISTINCT COALESCE(o.order_group_id, o.id)) through the cart's order |
carts_abandoned |
metric | COUNT(*) where incomplete and updated_at older than the store's window |
cart_conversion_rate |
metric | derived, ratio: %i[carts_converted carts_started], format: :percent |
abandoned_value |
metric | SUM(total) over the abandoned population, format: :money |
started_at |
dimension | time, grains: %i[hour day week month] |
cart_status |
dimension | expression → converted / abandoned / active, enumerated |
cart_channel |
dimension | channel_id, reusing the existing channel lookup |
carts_abandoned and abandoned_value read the same preference-driven
predicate, defined once and referenced by both — two definitions of "abandoned"
is the failure this decision exists to prevent.
Promotion dimensions (sales family, :line_items base, joined through
spree_discounts):
| Member | Kind | Definition |
|---|---|---|
promotion |
dimension | %{discounts}.promotion_id, lookup Spree::Promotion, subject: Spree::Promotion, key_scope: 'read_promotions' |
coupon_code |
dimension | %{discounts}.code, no lookup (the code is its own label) |
promotion_discounts |
metric | SUM(-%{discounts}.amount), format: :money |
promotion_redemptions |
metric | COUNT(DISTINCT COALESCE(order_group_id, id)) |
A discount_kind axis was considered and dropped: all three discount
dimensions join the same promotion-filtered association (two joins onto
spree_discounts would alias the second, and both would then read whichever
was joined first), so the kind could only ever report promotion — a field
with one possible value.
Both dimensions declare a subject, so a role without promotion access cannot
break down revenue by promotion — and, per the semantic layer's fail-closed
rule, declaring a subject obliges them to declare a key_scope too.
Lifetime metrics (sales family, :orders base): customer_lifetime_value
(money) and orders_lifetime (integer), both correlated subqueries over the
customer's whole history, both valid only grouped by customer.
Contract changes
metric_filters: [{ metric:, op:, value: }] # HAVING; ops eq|gt|gte|lt|lte
dimensions: [{ name:, grain:, include_empty: }] # include_empty is new
compare: "previous_period" | "previous_year" # previous_year is new
grains: hour | day | week | month # hour is new
Every addition is additive: an existing saved report parses and returns the same
numbers. GET /reporting/schema publishes the new ops, grains, compare modes
and the include_empty capability per dimension, so the picker builder and the
agent tool schema pick them up without a second source of truth.
Compiler work
HAVING—Adapters::Livegains anapply_metric_filtersthat appends to the grouped query only. The ungrouped totals query ignores metric filters by construction: the Total is the period's real figure, not the sum of the rows that survived a filter. (Rows already need not sum to the total under Decision 13; this is the same rule, and the docs say so in the same place.)include_empty— compiles the dimension's lookup relation as the left side of a LEFT JOIN onto the aggregate, withCOALESCE(metric, 0). Valid only with exactly one dimension, which must have alookup.hour— three branches intime_bucket_sqland three inexpected_buckets(zero-fill), plus theMAX_BUCKETSguard. Note the existing shape: an unhandled grain currently falls through everycaseand returnsnil, which group-bys a NULL — so the guard is that both methods learnhourtogether.previous_year— a calendar-year shift inprevious_time_range, with the Feb 29 → Feb 28 rule.- Cross-base join —
join_forcurrently hardcodes the single:line_items → order → :ordershop. The carts base reaches its order and the promotion dimensions reachspree_discounts, so this becomes a small declared map (base → dimension base → association path) rather than a third and fourthif.resolve_sql's fixed table map gains%{carts},%{discounts}and%{promotions}.
Docs
The metrics whose window or population is not what a reader assumes carry their
caveat in the schema description, not only in the guide: lifetime value
(ignores the range), abandoned carts (capped by the reaper), cart conversion
(not storefront conversion). The description is what the picker shows and what
the agent reads, so a caveat that lives only in Mintlify reaches neither.
Migration Path
No data migration and no schema change beyond the store preference. Every change is additive vocabulary or an additive contract key, so saved reports written against the current vocabulary keep running unchanged.
- Contract + compiler —
metric_filters,include_empty,hour,previous_year, the declared cross-base join map,MAX_BUCKETS. Specs at the compiler level, where the semantic layer's other numbers are proven. - Refusal messages — the two rewrites, with specs asserting the remedy is named (the message is the deliverable, so it is what the spec asserts).
- Promotion vocabulary — dimensions and metrics on
spree_discounts, including the order-side owner filter and the NULL-promotion group. - Carts family — the
abandoned_cart_after_hourspreference and its Settings field, the base, metrics and dimensions. - Lifetime metrics — with the ungrouped refusal.
- Schema, SDK, dashboard —
GET /reporting/schemapublishes the additions;@spree/admin-sdkcontract types gain the new keys; the picker builder grows a metric-filter row and the hour grain. New keys land in every locale file, not onlyen.json. - Seeded reports — the questions that prompted this plan become seeded
classics: abandoned carts, sales by promotion, sales by hour of day, never-sold
products, top customers by lifetime value. (Deferred — the vocabulary and
the builder answer all of them today; seeding is a separate change to
Seeds::SavedReportswith its own upgrade question, see Open Questions.)
Constraints on Current Work
- A cart metric is never an order metric with a filter. Carts are their own
base in their own family, anchored on
created_at; mixing the two clocks in one query is refused for the same reason sales and inventory are. - One definition of "abandoned", from the store preference, shared by every metric that uses it — and never a second window hardcoded in a query or a dashboard filter.
- Discount money sums
-amount. The column is non-positive by DB constraint; a metric that forgets this reports negative discounts. - Promotion joins filter the owner side explicitly.
spree_discountsrows areorder_idXORcart_id; a sales-family join that omits the filter mixes unpurchased cart discounts into revenue. - Metric filters never touch the ungrouped totals query. The Total stays the period's real figure.
include_emptyis opt-in and single-dimension, and only on a dimension with alookup.- A new grain is added to
time_bucket_sqlandexpected_bucketstogether — an unhandled grain falls through toniland silently groups by NULL rather than raising. - Lifetime metrics are grouped by
customeror refused, and say in their own description that they ignore the report's range. - Abandonment is incomplete + quiet, and nothing else (Decision 11) — the reaper's payment exclusion is a deletion-safety rule and must not be copied into a reporting predicate.
- The two refusals stay refusals.
total_salesis not made groupable by line-item dimensions, and families are not merged; only the messages improve. - Traffic conversion stays unavailable.
cart_conversion_rateis not renamed toconversion_rate, and no metric implies session data we do not have.
Open Questions
Seeding the new classics: the five reports this plan set out to make askable are all reachable through the builder, but none ships as a seeded row. Adding them means touching
Seeds::SavedReports, which the semantic layer plan already flags as unable to tell "never created" from "deliberately deleted" — so it waits on that question rather than adding five more rows a merchant cannot permanently remove.Should
promotionreach the orders base? The dimensions are registered on:line_itemsbecause that is where discount rows attach. "Orders that used promotion X" is a reasonable question that would need an id-subquery from the orders base; deferred until a merchant asks, since the filter path already supports it.Lifetime value and canceled history: the subquery excludes canceled orders, consistent with every sales metric. (Refunds settled — Decision 12.)
References
docs/plans/6.0-analytics-semantic-layer.md— the registry, contract, compiler and every decision this plan extends (especially 4 rejection, 7 timezone, 13 totals/LEFT joins, 14 families and correlated subqueries, 15 counters and store preferences).docs/plans/6.0-cart-order-split.md— theSpree::Carttable, thecart_iduniqueness that makes conversion safe to aggregate, and the tiered reaper that caps abandoned-cart history.spree/core/app/jobs/spree/carts/reap_expired_job.rb— the existing abandonment definition this plan adopts.spree/core/app/models/spree/discount.rb— per-row promotion attribution, the non-positive amount constraint, and the dual owner.spree/core/app/models/spree/promotion.rb—credits_countandcheckouts_credited, the checkout-identity rule for redemptions.