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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Renamed the operations endpoint to counters and gave the sidebar badges the same source
Damian Legawiec733444b5f424
diff --git a/docs/developer/core-concepts/reporting.mdx b/docs/developer/core-concepts/reporting.mdxindex cb0a17017c..3fabff95aa 100644--- a/docs/developer/core-concepts/reporting.mdx+++ b/docs/developer/core-concepts/reporting.mdx@@ -162,7 +162,7 @@ rule, so a picker never offers a dimension whose query would be refused.Not everything on the home screen is a report over a period. "Orders tofulfill", "Open returns" and "Low stock variants" are the state of the storeright now, with no time range and no currency. The registry holds these as-**counters** beside metrics and dimensions, and `GET /dashboard/operations`+**counters** beside metrics and dimensions, and `GET /dashboard/counters`evaluates them:```json@@ -183,6 +183,14 @@ evaluates them:}```+One request serves both surfaces that show these numbers: the home screen's+card and the sidebar's badges. A counter that badges a nav entry names it, so+the sidebar renders it without knowing which counters exist:++```json+{ "key": "open_returns", "label": "Open returns", "value": 3, "nav": "returns" }+```+Three things follow from counters living in the registry:- **Labels come from the server**, the same way metric labels do, so a@@ -196,8 +204,9 @@ Three things follow from counters living in the registry:registered together. A counter with no list that can honestly show what itcounted carries no link.-Core ships five: orders to fulfill, payments to collect, open returns, low-stock variants and out of stock variants. The low stock counter reads the+Core ships seven: orders to fulfill, payments to collect, open returns, open+exchanges, open claims, low stock variants and out of stock variants. The+three post-sale ones badge their sidebar entries. The low stock counter reads thestore's `low_stock_threshold` preference (default five units; zero turns itoff), which merchants set under store settings → Inventory.diff --git a/docs/developer/how-to/extend-reporting.mdx b/docs/developer/how-to/extend-reporting.mdxindex f61f826903..67ab510fb7 100644--- a/docs/developer/how-to/extend-reporting.mdx+++ b/docs/developer/how-to/extend-reporting.mdx@@ -165,7 +165,8 @@ Spree.reporting.counter :orders_on_hold,```Add `reporting.counters.orders_on_hold.label` (and optionally `.description`)-to your locale file; without an entry the name is humanized. Declare `link`+to your locale file; without an entry the name is humanized. Pass `nav:` with+a sidebar entry's key to badge that entry with this count. Declare `link`only when the list filter shows exactly the rows counted — the dashboardresolves `resource` to one of its lists (`orders`, `returns`, `products`) andappends the channel filter itself for order lists. A counter whose meaningdiff --git a/docs/plans/6.0-analytics-semantic-layer.md b/docs/plans/6.0-analytics-semantic-layer.mdindex 3dffcd0157..48ced30dfb 100644--- a/docs/plans/6.0-analytics-semantic-layer.md+++ b/docs/plans/6.0-analytics-semantic-layer.md@@ -4,7 +4,7 @@**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-10 (Decision 15: operations counters join the registry; low stock threshold becomes a store preference)+**Last updated:** 2026-09-11 (Decision 15: counters join the registry and serve the sidebar badges too; low stock threshold becomes a store preference)## Summary@@ -194,7 +194,7 @@ does not send us the data. That is now the only recorded gap.### Decision 15 — Operations counters are registry members; the low stock threshold is a store preference (2026-09-10)-The home screen's Operations card was the last hand-rolled number surface: five counts as private methods on a serializer in the API gem, five matching icon-plus-filter rows hardcoded in the dashboard, one permission (`read_dashboard`) covering all of them, and a `low_stock_threshold` request parameter the dashboard never sent. **Counters now join `Spree.reporting`** as a fourth member type beside metrics, dimensions and bases: `registry.counter :name, count: ->(store, channel:) { … }, subject:, key_scope:, link:, description:`. They are not compiled into the query (no range, no currency, no base — a counter is the state of the store at this instant), so the registry only stores the lambda; `Spree::Reporting::Counters` evaluates them for one store and channel, filtered by the same `member_allowed?` predicate the schema and the query apply, now shared through `Admin::ReportingAuthorization`. `GET /dashboard/operations` returns `{ channel_id, counters: [{ key, label, description, value, link }] }` and the dashboard renders whatever arrives, keeping only an icon map with a fallback. Labels resolve through `reporting.counters.<key>` in the locale the way metric labels do. **The link is declared beside the count** so the list a merchant lands on shows exactly the rows counted — the previous out-of-stock link pointed at a products filter the server silently dropped. **`low_stock_threshold` is a `Spree::Store` preference** (integer, default 5, 0 = off), edited under Settings → Store → Inventory and named in the counter's own description; neither reference platform has a per-variant threshold, and Shopify's inventory report bands by days of supply rather than a count, so store-level is the grain. Not `Spree.operations` (reserved) and not a second namespace — the plan's own line that "state metrics join the registry" is the design.+The home screen's Operations card was the last hand-rolled number surface: five counts as private methods on a serializer in the API gem, five matching icon-plus-filter rows hardcoded in the dashboard, one permission (`read_dashboard`) covering all of them, and a `low_stock_threshold` request parameter the dashboard never sent. **Counters now join `Spree.reporting`** as a fourth member type beside metrics, dimensions and bases: `registry.counter :name, count: ->(store, channel:) { … }, subject:, key_scope:, link:, description:`. They are not compiled into the query (no range, no currency, no base — a counter is the state of the store at this instant), so the registry only stores the lambda; `Spree::Reporting::Counters` evaluates them for one store and channel, filtered by the same `member_allowed?` predicate the schema and the query apply, now shared through `Admin::ReportingAuthorization`. `GET /dashboard/counters` returns `{ channel_id, counters: [{ key, label, description, value, link, nav }] }` and the dashboard renders whatever arrives, keeping only an icon map with a fallback. **One request serves the home card and every sidebar badge:** the three post-sale badges each used to spend a list request with `limit: 1` purely to read a total off the pagination meta, and the returns badge counted `received` while the counter did not — two definitions of the same number. Counters now carry the nav entry they badge, so the sidebar reads the shared response and an extension's counter badges its own entry with no dashboard release. Labels resolve through `reporting.counters.<key>` in the locale the way metric labels do. **The link is declared beside the count** so the list a merchant lands on shows exactly the rows counted — the previous out-of-stock link pointed at a products filter the server silently dropped. **`low_stock_threshold` is a `Spree::Store` preference** (integer, default 5, 0 = off), edited under Settings → Store → Inventory and named in the counter's own description; neither reference platform has a per-variant threshold, and Shopify's inventory report bands by days of supply rather than a count, so store-level is the grain. Not `Spree.operations` (reserved) and not a second namespace — the plan's own line that "state metrics join the registry" is the design.## Design Details@@ -320,6 +320,7 @@ 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`; a point-in-time count for the home screen is a registered **counter** evaluated by `dashboard/operations` — never a new method on a serializer, and never a number the dashboard computes or labels itself.+- **A count shown in the shell is a counter**, read from the shared endpoint — never a list request with `limit: 1` for its `meta.count`, which costs a round trip per badge and invents a second definition of the number.- **A counter's link is declared beside its count**, or not at all: the list a number opens must show exactly the rows counted. Stock counters carry no link until an inventory list can filter by on-hand quantity (`6.0-inventory-operations.md` Phase 7).- **Every surface that lists vocabulary members filters through `ReportingAuthorization#member_allowed?`** — metrics, dimensions and counters declare `subject` + `key_scope` alike; no endpoint gets a second predicate.- **The low stock threshold is the store's `low_stock_threshold` preference**, read through `preferred_low_stock_threshold`; no request parameter, no global, no per-variant column.diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 68aa5cac4b..165ec47e6c 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,10 +1,12 @@-## 2026-09-10: Home-screen operations counters are reporting registry members+## 2026-09-11: Counters are reporting registry members, and one request serves the home card and the sidebar**Context:** `dashboard/operations` served five counts as private methods on a serializer in the API gem, the dashboard hardcoded the matching rows (icons, labels, deep-link filters), one permission covered all five, and the out-of-stock deep link pointed at a products filter the server silently dropped. The low stock threshold was a request parameter with a hardcoded default that nothing sent.**Decision:** Counters are a fourth member type on `Spree.reporting` (`registry.counter`), evaluated by `Spree::Reporting::Counters` rather than compiled into the query — a counter has no range, currency or base. Each declares `subject` + `key_scope` like every other member and is filtered by the shared `Admin::ReportingAuthorization#member_allowed?`; the endpoint returns `{ key, label, description, value, link }` per counter and the dashboard renders whatever arrives. The link is declared beside the count so the list opened shows exactly the rows counted; a counter with no honest list (the stock ones, until the Inventory page) carries none. `low_stock_threshold` is a `Spree::Store` preference (default 5, 0 = off) surfaced in store settings. `Spree.operations` stays reserved; the registry name `Spree.reporting` is unchanged.-**Consequences:** An extension registers a counter with a locale label and it appears on every merchant's home screen with the right permission gating and no dashboard change. A limited role sees a shorter list, not a refused card. New point-in-time numbers for the home screen are registrations — never serializer methods or client-side derivations. See `6.0-analytics-semantic-layer.md` Decision 15.+**Amended 2026-09-11:** the endpoint is `dashboard/counters`, not `dashboard/operations` — the payload was already named after what it holds, and the developer preview needs no bridge. The three post-sale sidebar badges fold into it: each used to issue its own list request with `limit: 1` to read a total off the pagination meta, so the shell spent three round trips counting three things, and the returns badge counted `received` while `open_returns` did not. Counters now carry the `nav` entry they badge, `open_exchanges` and `open_claims` join the vocabulary, `open_returns` adopts the badge's wider definition, and the sidebar and home card share one query.++**Consequences:** An extension registers a counter with a locale label and it appears on every merchant's home screen — and, with `nav`, in the sidebar — with the right permission gating and no dashboard change. A limited role sees a shorter list, not a refused card. New point-in-time numbers for the home screen are registrations — never serializer methods or client-side derivations. See `6.0-analytics-semantic-layer.md` Decision 15.## 2026-09-10: Close-short writes the incoming counter, the Inventory page opens on every location, and the recount is an upgrade stepdiff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 2baa5bf2be..ca2f5fae17 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -120,13 +120,14 @@ export interface ReportingSchema {limits: { default: number; max: number }}-export interface DashboardOperations {+export interface DashboardCounters {/** Prefixed channel id the order-based counts are scoped to; null means all channels. Stock counts are always store-wide. */channel_id: string | null/*** The counters registered on `Spree.reporting` that this caller may read,- * in registration order. Labels and links come from the server, so a- * counter an extension registers renders without a dashboard change.+ * in registration order. Labels, links and the sidebar entry each one+ * badges all come from the server, so a counter an extension registers+ * renders without a dashboard change.*/counters: DashboardCounter[]}@@ -913,11 +914,11 @@ export class AdminClient {}readonly dashboard = {- operations: (+ counters: (params?: { channel_id?: string },options?: RequestOptions,- ): Promise<DashboardOperations> =>- this.request<DashboardOperations>('GET', '/dashboard/operations', { ...options, params }),+ ): Promise<DashboardCounters> =>+ this.request<DashboardCounters>('GET', '/dashboard/counters', { ...options, params }),}// ============================================diff --git a/packages/admin-sdk/src/index.ts b/packages/admin-sdk/src/index.tsindex 203d883154..3fc5ba4d53 100644--- a/packages/admin-sdk/src/index.ts+++ b/packages/admin-sdk/src/index.ts@@ -7,7 +7,7 @@ export type {AuthProvider,AuthProvidersResponse,AuthTokens,- DashboardOperations,+ DashboardCounters,LoginCredentials,MeResponse,PermissionRule,diff --git a/packages/admin-sdk/src/types/generated/DashboardCounter.ts b/packages/admin-sdk/src/types/generated/DashboardCounter.tsindex 5a44e9d245..abc08fc0a7 100644--- a/packages/admin-sdk/src/types/generated/DashboardCounter.ts+++ b/packages/admin-sdk/src/types/generated/DashboardCounter.ts@@ -1,4 +1,4 @@-// Typelizer digest aa3687c1a949ba4231ccf94aaef269f4+// Typelizer digest ed2550e3d4e2bac657a938ea85c64127//// DO NOT MODIFY: This file was automatically generated by Typelizer.@@ -9,6 +9,8 @@ interface DashboardCounter {value: number;/** The list filter that shows exactly the rows counted, or null when no list can. */link: { resource: string; filters: Array<{ field: string; operator: string; value: string }> } | null;+ /** Sidebar entry key this count badges, or null. */+ nav: string | null;}export default DashboardCounter;diff --git a/packages/admin-sdk/tests/store-settings.test.ts b/packages/admin-sdk/tests/store-settings.test.tsindex 57277f63e3..ad5c5afb53 100644--- a/packages/admin-sdk/tests/store-settings.test.ts+++ b/packages/admin-sdk/tests/store-settings.test.ts@@ -98,20 +98,19 @@ describe('reporting', () => {})describe('dashboard', () => {- describe('operations', () => {- it('GETs /dashboard/operations and forwards optional params', async () => {+ describe('counters', () => {+ it('GETs /dashboard/counters and forwards the channel', async () => {let url: URL | null = nullserver.use(- http.get(`${API_PREFIX}/dashboard/operations`, ({ request }) => {+ http.get(`${API_PREFIX}/dashboard/counters`, ({ request }) => {url = new URL(request.url)- return HttpResponse.json({ orders_to_fulfill: 0 })+ return HttpResponse.json({ channel_id: 'ch_1', counters: [] })}),)- await createTestClient().dashboard.operations({ channel_id: 'ch_1', low_stock_threshold: 3 })+ await createTestClient().dashboard.counters({ channel_id: 'ch_1' })expect(url!.searchParams.get('channel_id')).toBe('ch_1')- expect(url!.searchParams.get('low_stock_threshold')).toBe('3')})})})diff --git a/packages/dashboard/src/components/spree/nav-counter-badge.tsx b/packages/dashboard/src/components/spree/nav-counter-badge.tsxnew file mode 100644index 0000000000..37137d082b--- /dev/null+++ b/packages/dashboard/src/components/spree/nav-counter-badge.tsx@@ -0,0 +1,28 @@+import { Badge } from '@spree/dashboard-ui'+import { useDashboardCounters } from '../../hooks/use-dashboard-counters'++/**+ * How many records under a nav entry still need the merchant to do something.+ *+ * The count comes from the counters endpoint, which every badge and the home+ * screen's card share as one request — the sidebar used to spend a list+ * request per badge just to read a total off the pagination meta. Which nav+ * entry a counter badges is the counter's own `nav` field, so an extension+ * registering a counter badges its nav entry without a dashboard release.+ */+export function navCounterBadge(navKey: string) {+ return function NavCounterBadge() {+ const { data } = useDashboardCounters()+ const total = (data?.counters ?? [])+ .filter((counter) => counter.nav === navKey)+ .reduce((sum, counter) => sum + counter.value, 0)++ if (total === 0) return null++ return (+ <Badge variant="outline" className="rounded-lg mr-1">+ {total}+ </Badge>+ )+ }+}diff --git a/packages/dashboard/src/components/spree/post-sale-nav-badges.tsx b/packages/dashboard/src/components/spree/post-sale-nav-badges.tsxdeleted file mode 100644index e7f1bacdcf..0000000000--- a/packages/dashboard/src/components/spree/post-sale-nav-badges.tsx+++ /dev/null@@ -1,65 +0,0 @@-import { adminClient, useResourceKey } from '@spree/dashboard-core'-import { Badge } from '@spree/dashboard-ui'-import { useQuery } from '@tanstack/react-query'--/**- * How many records still need the merchant to do something. Asks for a single- * row and reads the total off the pagination meta, so the sidebar never pulls- * a full page it does not render.- *- * Ransack predicates go at the top level — `transformListParams` wraps every- * key it does not recognise in `q[...]`, so nesting them under `q` produces- * `q[q]` and the filter is silently ignored.- */-function usePendingCount(- resourceKey: string,- statuses: string[],- list: (params: Record<string, unknown>) => Promise<{ meta?: { count?: number } }>,-) {- const { data } = useQuery({- queryKey: useResourceKey(`${resourceKey}-pending`),- queryFn: () => list({ limit: 1, status_in: statuses }),- // Deliberately no staleTime: acting on a record invalidates this key, and- // a stale window would hold the old count past that invalidation.- })-- return data?.meta?.count ?? 0-}--function CountBadge({ count }: { count: number }) {- if (count === 0) return null-- return (- <Badge variant="outline" className="rounded-lg mr-1">- {count}- </Badge>- )-}--// Everything still in flight, not just the first step: an approved return-// still needs receiving and refunding, so it is as much outstanding work as-// one nobody has looked at. Terminal statuses — refunded, fulfilled,-// resolved, denied, canceled — are done and drop out of the count.-const RETURNS_IN_PROGRESS = ['requested', 'approved', 'received']-const EXCHANGES_IN_PROGRESS = ['requested', 'approved', 'received']-const CLAIMS_IN_PROGRESS = ['open', 'approved']--export function ReturnsNavBadge() {- return (- <CountBadge count={usePendingCount('returns', RETURNS_IN_PROGRESS, adminClient.returns.list)} />- )-}--export function ExchangesNavBadge() {- return (- <CountBadge- count={usePendingCount('exchanges', EXCHANGES_IN_PROGRESS, adminClient.exchanges.list)}- />- )-}--export function ClaimsNavBadge() {- return (- <CountBadge count={usePendingCount('claims', CLAIMS_IN_PROGRESS, adminClient.claims.list)} />- )-}diff --git a/packages/dashboard/src/hooks/use-dashboard-counters.ts b/packages/dashboard/src/hooks/use-dashboard-counters.tsnew file mode 100644index 0000000000..db71787f91--- /dev/null+++ b/packages/dashboard/src/hooks/use-dashboard-counters.ts@@ -0,0 +1,36 @@+import type { DashboardCounter } from '@spree/admin-sdk'+import { adminClient, useResourceKey } from '@spree/dashboard-core'+import { useQuery } from '@tanstack/react-query'++/**+ * The point-in-time counts registered on `Spree.reporting`: what needs the+ * merchant's attention right now.+ *+ * One request serves the home screen's card and every sidebar badge — the+ * key is the channel, so the unscoped call the sidebar makes is shared with+ * the home screen whenever no channel is selected. Counters the caller may+ * not read are absent from the response rather than zero, so a badge for one+ * simply never renders.+ *+ * @param channelId prefixed channel id, or undefined for all channels+ */+export function useDashboardCounters(channelId?: string) {+ return useQuery({+ queryKey: useResourceKey('dashboard', 'counters', channelId),+ queryFn: () => adminClient.dashboard.counters({ channel_id: channelId }),+ // No `placeholderData`: it would belong to the channel selected before,+ // and showing another channel's counts under this one's name is worse+ // than showing the skeleton for a moment.+ staleTime: 5 * 60 * 1000,+ })+}++/**+ * One counter by key, or undefined when it is still loading, absent, or the+ * caller cannot read it.+ */+export function useDashboardCounter(key: string): DashboardCounter | undefined {+ const { data } = useDashboardCounters()++ return data?.counters.find((counter) => counter.key === key)+}diff --git a/packages/dashboard/src/nav/default.ts b/packages/dashboard/src/nav/default.tsindex 3191537349..3c8cf17c0d 100644--- a/packages/dashboard/src/nav/default.ts+++ b/packages/dashboard/src/nav/default.ts@@ -15,11 +15,7 @@ import {WarehouseIcon,} from '@spree/dashboard-ui/icons'import { GettingStartedNavBadge } from '../components/spree/getting-started-nav-badge'-import {- ClaimsNavBadge,- ExchangesNavBadge,- ReturnsNavBadge,-} from '../components/spree/post-sale-nav-badges'+import { navCounterBadge } from '../components/spree/nav-counter-badge'nav.add({key: 'getting-started',@@ -68,7 +64,7 @@ nav.add({path: '/returns',subject: Subject.Order,position: 200,- badge: ReturnsNavBadge,+ badge: navCounterBadge('returns'),},{key: 'exchanges',@@ -76,7 +72,7 @@ nav.add({path: '/exchanges',subject: Subject.Order,position: 300,- badge: ExchangesNavBadge,+ badge: navCounterBadge('exchanges'),},{key: 'claims',@@ -84,7 +80,7 @@ nav.add({path: '/claims',subject: Subject.Order,position: 400,- badge: ClaimsNavBadge,+ badge: navCounterBadge('claims'),},],})diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsxindex 94df18ae93..01517f25c3 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx@@ -1,14 +1,6 @@-import type { DashboardCounter, DashboardOperations, ReportingQuery } from '@spree/admin-sdk'+import type { DashboardCounter, DashboardCounters, ReportingQuery } from '@spree/admin-sdk'import { SpreeError } from '@spree/admin-sdk'-import {- adminClient,- Can,- resolveDatePreset,- Subject,- usePermissions,- useResourceKey,- useStore,-} from '@spree/dashboard-core'+import { Can, resolveDatePreset, Subject, usePermissions, useStore } from '@spree/dashboard-core'import {Button,Card,@@ -50,7 +42,6 @@ import {TriangleAlertIcon,TruckIcon,} from '@spree/dashboard-ui/icons'-import { useQuery } from '@tanstack/react-query'import { createFileRoute, Link, type LinkProps } from '@tanstack/react-router'import { format, parseISO } from 'date-fns'import type { CSSProperties } from 'react'@@ -65,6 +56,7 @@ import {sharePercent,TimeSeriesChart,} from '../../../components/spree/reporting/report-view'+import { useDashboardCounters } from '../../../hooks/use-dashboard-counters'import {entityDimension,metaString,@@ -133,14 +125,7 @@ function DashboardPage() {? resolveMetrics(CHART_METRICS, schema): CHART_METRICS.map((name) => ({ name, label: name, format: 'decimal', derived: false }))- // No `placeholderData`: it belongs to the channel that was selected before,- // and showing another channel's counts under this one's name is worse than- // showing the skeleton for a moment.- const { data: operations, error: operationsError } = useQuery({- queryKey: useResourceKey('dashboard', 'operations', channelId),- queryFn: () => adminClient.dashboard.operations({ channel_id: channelParam }),- staleTime: 5 * 60 * 1000,- })+ const { data: operations, error: operationsError } = useDashboardCounters(channelParam)// A role without `read_reports` (or order data) gets a 403 here — say so// rather than leaving the skeleton up forever. Any other failure is a plain@@ -276,7 +261,7 @@ function OperationsCard({channelId,failed,}: {- data: DashboardOperations | undefined+ data: DashboardCounters | undefinedclassName: string/** The screen's channel, or undefined for all channels. */channelId: string | undefineddiff --git a/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rbindex 125ff21ae3..23ef037cd1 100644--- a/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb@@ -2,21 +2,22 @@ module Spreemodule Apimodule V3module Admin- # Point-in-time operational counts for the dashboard home, evaluated- # from the counters registered on Spree.reporting. Time-series- # analytics live in the semantic reporting endpoint (ReportingController).+ # Point-in-time counts registered on Spree.reporting: what needs the+ # merchant's attention right now, for the home screen's card and the+ # sidebar's badges. Time-series analytics live in the semantic+ # reporting endpoint (ReportingController).class DashboardController < Admin::BaseControllerinclude ReportingAuthorizationscoped_resource :dashboard- # GET /api/v3/admin/dashboard/operations+ # GET /api/v3/admin/dashboard/counters## Filtered to the counters this caller may read, so a limited role# gets a shorter list rather than a refused card.- def operations+ def counterschannel = requested_channel- counters = Spree::Reporting::Counters.new(+ evaluated = Spree::Reporting::Counters.new(store: current_store,channel: channel,allowed: ->(counter) { member_allowed?(counter) }@@ -24,7 +25,7 @@ module Spreerender json: {channel_id: channel&.prefixed_id,- counters: DashboardCounterSerializer.new(counters.to_a).serializable_hash+ counters: DashboardCounterSerializer.new(evaluated.to_a).serializable_hash}enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/dashboard_counter_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/dashboard_counter_serializer.rbindex a17593a79a..6c2a8b5eed 100644--- a/spree/api/app/serializers/spree/api/v3/admin/dashboard_counter_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/dashboard_counter_serializer.rb@@ -10,9 +10,10 @@ module Spreetypelize key: :string, label: :string, description: [:string, nullable: true], value: :number,link: ['{ resource: string; filters: Array<{ field: string; operator: string; value: string }> } | null',- comment: 'The list filter that shows exactly the rows counted, or null when no list can.']+ comment: 'The list filter that shows exactly the rows counted, or null when no list can.'],+ nav: [:string, nullable: true, comment: 'Sidebar entry key this count badges, or null.']- attributes :key, :label, :description, :value, :link+ attributes :key, :label, :description, :value, :link, :navendendenddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex a06a976bae..1b38e5c22c 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -252,9 +252,9 @@ Spree::Core::Engine.add_routes doresources :saved_reports, only: %i[index show create update destroy]end- # Dashboard (point-in-time operational counts)+ # Dashboard (point-in-time counts registered on Spree.reporting)namespace :dashboard do- get :operations+ get :countersend# Current admin user + permissions (for UI permission checks)diff --git a/spree/api/spec/controllers/spree/api/v3/admin/dashboard_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/dashboard_controller_spec.rbindex 4850dd87f8..1f17f94ee3 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/dashboard_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/dashboard_controller_spec.rb@@ -7,8 +7,8 @@ RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller dobefore { request.headers.merge!(headers) }- describe 'GET #operations' do- subject { get :operations, as: :json }+ describe 'GET #counters' do+ subject { get :counters, as: :json }let(:counter_keys) { json_response['counters'].map { |counter| counter['key'] } }@@ -17,10 +17,12 @@ RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller doexpect(response).to have_http_status(:ok)expect(json_response['channel_id']).to be_nil- expect(counter_keys).to eq(%w[orders_to_fulfill payments_to_collect open_returns low_stock_items out_of_stock_items])+ expect(counter_keys).to eq(+ %w[orders_to_fulfill payments_to_collect open_returns open_exchanges open_claims low_stock_items out_of_stock_items]+ )fulfill = json_response['counters'].first- expect(fulfill).to include('label' => 'Orders to fulfill', 'value' => 0)+ expect(fulfill).to include('label' => 'Orders to fulfill', 'value' => 0, 'nav' => nil)expect(fulfill['link']).to eq('resource' => 'orders','filters' => [{ 'field' => 'fulfillment_status', 'operator' => 'eq', 'value' => 'unfulfilled' }]@@ -32,16 +34,23 @@ RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller docreate(:order_ready_to_ship, store: store)create(:order_ready_to_ship, store: store, channel: channel)- get :operations, params: { channel_id: channel.prefixed_id }, as: :json+ get :counters, params: { channel_id: channel.prefixed_id }, as: :jsonexpect(json_response['channel_id']).to eq(channel.prefixed_id)expect(json_response['counters'].find { |c| c['key'] == 'orders_to_fulfill' }['value']).to eq(1)end+ it 'names the sidebar entry a post-sale counter badges' do+ subject++ returns = json_response['counters'].find { |counter| counter['key'] == 'open_returns' }+ expect(returns['nav']).to eq('returns')+ end+it 'refuses a channel from another store' doother_channel = create(:channel, store: create(:store))- get :operations, params: { channel_id: other_channel.prefixed_id }, as: :json+ get :counters, params: { channel_id: other_channel.prefixed_id }, as: :jsonexpect(response).to have_http_status(:not_found)enddiff --git a/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb b/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rbindex 9825d1cadc..b19ca3cdf5 100644--- a/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb@@ -188,7 +188,7 @@ RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller dolet(:scopes) { ['read_dashboard'] }it 'enforces the scope and allows the read' do- get :operations, as: :json+ get :counters, as: :jsonexpect(response).to have_http_status(:ok)endend@@ -197,7 +197,7 @@ RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller dolet(:scopes) { ['read_orders'] }it 'denies rather than silently skipping the scope check' do- get :operations, as: :json+ get :counters, as: :jsonexpect(response).to have_http_status(:forbidden)body = JSON.parse(response.body)@@ -214,7 +214,7 @@ RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller doendit 'passes the key gate (admin holds the full catalog)' do- get :operations, as: :json+ get :counters, as: :jsonexpect(response).to have_http_status(:ok)endenddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex fcd458d357..254127a9fd 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1692,8 +1692,14 @@ en:other: "%{count} units or fewer on hand at an active location."zero: Turned off. Set a low stock threshold in store settings to use this.label: Low stock variants+ open_claims:+ description: Claims still open or approved and not yet resolved.+ label: Open claims+ open_exchanges:+ description: Exchanges not yet fulfilled.+ label: Open exchangesopen_returns:- description: Returns requested or approved and not yet received.+ description: Returns not yet refunded.label: Open returnsorders_to_fulfill:description: Placed orders with nothing shipped yet.diff --git a/spree/core/lib/spree/reporting/counter_result.rb b/spree/core/lib/spree/reporting/counter_result.rbindex 78caf82f22..618be36768 100644--- a/spree/core/lib/spree/reporting/counter_result.rb+++ b/spree/core/lib/spree/reporting/counter_result.rb@@ -13,6 +13,8 @@ module Spreeattribute :value, :integer# `{ resource:, filters: [...] }` as registered, or nil.attribute :link+ # Sidebar entry key this count badges, or nil.+ attribute :nav, :stringendendenddiff --git a/spree/core/lib/spree/reporting/counters.rb b/spree/core/lib/spree/reporting/counters.rbindex 4daa658878..5b0f72feca 100644--- a/spree/core/lib/spree/reporting/counters.rb+++ b/spree/core/lib/spree/reporting/counters.rb@@ -25,7 +25,8 @@ module Spreelabel: translate(counter.name, :label) || counter.name.to_s.humanize,description: description_for(counter),value: counter.count.call(@store, channel: @channel),- link: counter.link&.deep_stringify_keys+ link: counter.link&.deep_stringify_keys,+ nav: counter.nav)endenddiff --git a/spree/core/lib/spree/reporting/default_vocabulary.rb b/spree/core/lib/spree/reporting/default_vocabulary.rbindex 76e7d00fdf..9754a2f70d 100644--- a/spree/core/lib/spree/reporting/default_vocabulary.rb+++ b/spree/core/lib/spree/reporting/default_vocabulary.rb@@ -88,12 +88,24 @@ module SpreeendPAYMENTS_OWED = %w[none authorized partially_paid].freeze- OPEN_RETURN_STATUSES = %w[requested approved].freeze++ # Everything still in flight, not just the first step: an approved return+ # still needs receiving and refunding, so it is as much outstanding work+ # as one nobody has looked at. Terminal statuses drop out.+ OPEN_RETURN_STATUSES = %w[requested approved received].freeze+ OPEN_EXCHANGE_STATUSES = %w[requested approved received].freeze+ OPEN_CLAIM_STATUSES = %w[open approved].freeze# Placed orders a merchant still acts on, narrowed to a channel when one# is being looked at.PLACED_ORDERS = ->(store, channel) { store.orders.complete.not_canceled.for_channel(channel) }+ # Post-sale records still owed work. All three hang off an order, which+ # is how a channel narrows them.+ OPEN_POST_SALE = lambda { |relation, channel, statuses|+ relation.joins(:order).where(status: statuses).merge(Spree::Order.for_channel(channel)).count+ }+# Stock a merchant is actually counting: tracked variants at active# locations. `store.stock_levels` walks products → variants, so paranoia# default scopes already exclude deleted products and variants.@@ -424,14 +436,23 @@ module Spreefilters: [{ field: 'payment_status', operator: 'in', value: PAYMENTS_OWED.join(',') }] }counter :open_returns,- subject: -> { Spree::Return }, key_scope: 'read_orders',- count: lambda { |store, channel:|- store.returns.joins(:order).where(status: OPEN_RETURN_STATUSES).- merge(Spree::Order.for_channel(channel)).count- },+ subject: -> { Spree::Return }, key_scope: 'read_orders', nav: 'returns',+ count: ->(store, channel:) { OPEN_POST_SALE.call(store.returns, channel, OPEN_RETURN_STATUSES) },link: { resource: 'returns',filters: [{ field: 'status', operator: 'in', value: OPEN_RETURN_STATUSES.join(',') }] }+ counter :open_exchanges,+ subject: -> { Spree::Exchange }, key_scope: 'read_orders', nav: 'exchanges',+ count: ->(store, channel:) { OPEN_POST_SALE.call(store.exchanges, channel, OPEN_EXCHANGE_STATUSES) },+ link: { resource: 'exchanges',+ filters: [{ field: 'status', operator: 'in', value: OPEN_EXCHANGE_STATUSES.join(',') }] }++ counter :open_claims,+ subject: -> { Spree::Claim }, key_scope: 'read_orders', nav: 'claims',+ count: ->(store, channel:) { OPEN_POST_SALE.call(store.claims, channel, OPEN_CLAIM_STATUSES) },+ link: { resource: 'claims',+ filters: [{ field: 'status', operator: 'in', value: OPEN_CLAIM_STATUSES.join(',') }] }+counter :low_stock_items,subject: -> { Spree::StockLevel }, key_scope: 'read_stock',count: lambda { |store, channel:|diff --git a/spree/core/lib/spree/reporting/registry.rb b/spree/core/lib/spree/reporting/registry.rbindex e149918bd8..45ad5b72ab 100644--- a/spree/core/lib/spree/reporting/registry.rb+++ b/spree/core/lib/spree/reporting/registry.rb@@ -124,7 +124,12 @@ module Spree# @!attribute description# ->(store) returning a sentence, for counters whose meaning depends on# a store setting (a threshold). Omitted = the locale's static text.- Counter = Struct.new(:name, :count, :subject, :key_scope, :link, :description, keyword_init: true)+ # @!attribute nav+ # Key of the sidebar entry this count badges, when it badges one. The+ # dashboard reads it rather than mapping counter names to nav entries+ # itself, so an extension's counter can badge its own nav entry without+ # a dashboard release.+ Counter = Struct.new(:name, :count, :subject, :key_scope, :link, :description, :nav, keyword_init: true)# Allowlist of queryable metrics, dimensions and counters. One global# instance lives at `Spree.reporting`; core seeds the starter vocabulary in@@ -188,14 +193,15 @@ module Spree# @param count [Proc] ->(store, channel:) → Integer# @param link [Hash, nil] `{ resource:, filters: [{ field:, operator:, value: }] }`# @param description [Proc, nil] ->(store) → String- def counter(name, replace: false, count:, subject: nil, key_scope: nil, link: nil, description: nil)+ # @param nav [String, nil] sidebar entry key this count badges+ def counter(name, replace: false, count:, subject: nil, key_scope: nil, link: nil, description: nil, nav: nil)name = name.to_symraise ArgumentError, "counter #{name} already registered (pass replace: true to override)" if @counters.key?(name) && !replaceraise ArgumentError, "counter #{name} declares a subject and must also declare its key_scope" if subject && key_scope.blank?raise ArgumentError, "counter #{name} needs a callable count" unless count.respond_to?(:call)@counters[name] = Counter.new(name: name, count: count, subject: subject, key_scope: key_scope,- link: link, description: description)+ link: link, description: description, nav: nav)enddef metric!(name)diff --git a/spree/core/spec/lib/spree/reporting/counters_spec.rb b/spree/core/spec/lib/spree/reporting/counters_spec.rbindex 301c0dd334..f4dbc48642 100644--- a/spree/core/spec/lib/spree/reporting/counters_spec.rb+++ b/spree/core/spec/lib/spree/reporting/counters_spec.rb@@ -10,8 +10,11 @@ RSpec.describe Spree::Reporting::Counters doit 'evaluates every registered counter with a localized label and its link' doresults = evaluate- expect(results.keys).to eq(%w[orders_to_fulfill payments_to_collect open_returns low_stock_items out_of_stock_items])+ expect(results.keys).to eq(+ %w[orders_to_fulfill payments_to_collect open_returns open_exchanges open_claims low_stock_items out_of_stock_items]+ )expect(results['orders_to_fulfill'].label).to eq('Orders to fulfill')+ expect(results['orders_to_fulfill'].nav).to be_nilexpect(results['orders_to_fulfill'].link).to eq('resource' => 'orders','filters' => [{ 'field' => 'fulfillment_status', 'operator' => 'eq', 'value' => 'unfulfilled' }]@@ -58,12 +61,32 @@ RSpec.describe Spree::Reporting::Counters doendend- context 'with an open return' do+ context 'with post-sale records' dolet!(:open_return) { create(:return) }- it 'counts requested and approved returns' do+ it 'counts everything still in flight, and names the nav entry it badges' do+ result = evaluate['open_returns']++ expect(result.value).to eq(1)+ expect(result.nav).to eq('returns')+ end++ it 'counts a received return, which still needs refunding' do+ open_return.update!(status: 'received')+expect(evaluate['open_returns'].value).to eq(1)end++ it 'ignores a refunded return' do+ open_return.update!(status: 'refunded')++ expect(evaluate['open_returns'].value).to eq(0)+ end++ it 'counts exchanges and claims on their own nav entries' do+ expect(evaluate['open_exchanges'].nav).to eq('exchanges')+ expect(evaluate['open_claims'].nav).to eq('claims')+ endendcontext 'with stock levels' do