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.

Add a semantic reporting layer and rebuild the dashboard home on it

Damian Legawiec0d30b74b43fd
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 5ee4c7d22d..1012ab9b36 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -10,35 +10,74 @@ import type {
} from '@spree/sdk-core'
import { getParams, transformListParams } from '@spree/sdk-core'
-export interface DashboardAnalytics {
- currency: string
- date_from: string
- date_to: string
- summary: {
- sales_total: number
- display_sales_total: string
- sales_growth: number
- orders_count: number
- orders_growth: number
- avg_order_value: number
- display_avg_order_value: string
- avg_order_value_growth: number
+// ============================================
+// Semantic reporting contract (docs/plans/6.0-analytics-semantic-layer.md)
+// ============================================
+
+export interface ReportingQuery {
+ /** Registered metric names — discover via `reporting.schema()`. */
+ metrics: string[]
+ dimensions?: Array<string | { name: string; grain?: 'day' | 'month' }>
+ filters?: Array<{ dimension: string; op: 'eq' | 'in'; value: string | string[] }>
+ /** ISO datetimes/dates or relative (`"-30d"`); defaults to the last 30 days. */
+ time_range?: { since?: string; until?: string }
+ compare?: 'previous_period'
+ /** Metric name, `-` prefix for descending. */
+ sort?: string
+ limit?: number
+ currency?: string
+}
+
+export interface ReportingMetricValue {
+ value: number
+ /** Formatted money string — present on money metrics only. */
+ display?: string
+ /** Present when the query requested a comparison. */
+ previous?: number
+ /** Percentage change vs the previous period; null when there is no baseline. */
+ growth?: number | null
+}
+
+/** Hydrated display payload for lookup-backed dimensions. */
+export interface ReportingDimensionValue {
+ /** Prefixed id (e.g. `cust_…`); null when the underlying record is gone (e.g. guest customers). */
+ id: string | null
+ label: string
+ meta: Record<string, unknown>
+}
+
+export interface ReportingRow {
+ /** Raw values for plain dimensions (time buckets, statuses); display payloads for lookups. */
+ dimensions: Record<string, string | ReportingDimensionValue>
+ metrics: Record<string, ReportingMetricValue>
+}
+
+export interface ReportingResult {
+ meta: {
+ currency: string
+ time_range: { since: string; until: string }
+ previous_time_range: { since: string; until: string } | null
+ metrics: string[]
+ dimensions: Array<{ name: string; grain?: string }>
}
- chart_data: Array<{
- date: string
- sales: number
- orders: number
- avg_order_value: number
- }>
- top_products: Array<{
- id: string
- name: string
- slug: string
- image_url: string | null
- price: string | null
- quantity: number
- total: string
- }>
+ totals: Record<string, ReportingMetricValue>
+ rows: ReportingRow[]
+}
+
+export interface ReportingSchema {
+ metrics: Array<{ name: string; format: string; derived: boolean }>
+ dimensions: Array<{ name: string; type: string; grains?: string[]; lookup?: string }>
+}
+
+export interface DashboardOperations {
+ /** Prefixed channel id the order-based counts are scoped to; null means all channels. Stock counts are always store-wide. */
+ channel_id: string | null
+ low_stock_threshold: number
+ orders_to_fulfill: number
+ payments_to_collect: number
+ open_returns: number
+ low_stock_items: number
+ out_of_stock_items: number
}
export interface AuthTokens {
@@ -777,15 +816,22 @@ export class AdminClient {
// Dashboard
// ============================================
+ readonly reporting = {
+ /** Run a semantic reporting query against the registered metric/dimension vocabulary. */
+ query: (query: ReportingQuery, options?: RequestOptions): Promise<ReportingResult> =>
+ this.request<ReportingResult>('POST', '/reporting/query', { ...options, body: query }),
+
+ /** Registry introspection — drives pickers and agent tool schemas. */
+ schema: (options?: RequestOptions): Promise<ReportingSchema> =>
+ this.request<ReportingSchema>('GET', '/reporting/schema', options),
+ }
+
readonly dashboard = {
- analytics: (
- params?: { date_from?: string; date_to?: string; currency?: string },
+ operations: (
+ params?: { low_stock_threshold?: number; channel_id?: string },
options?: RequestOptions,
- ): Promise<DashboardAnalytics> =>
- this.request<DashboardAnalytics>('GET', '/dashboard/analytics', {
- ...options,
- params: params as Record<string, string>,
- }),
+ ): Promise<DashboardOperations> =>
+ this.request<DashboardOperations>('GET', '/dashboard/operations', { ...options, params }),
}
// ============================================
diff --git a/packages/admin-sdk/src/index.ts b/packages/admin-sdk/src/index.ts
index 393fb5041f..290c95488f 100644
--- a/packages/admin-sdk/src/index.ts
+++ b/packages/admin-sdk/src/index.ts
@@ -7,10 +7,16 @@ export type {
AuthProvider,
AuthProvidersResponse,
AuthTokens,
- DashboardAnalytics,
+ DashboardOperations,
LoginCredentials,
MeResponse,
PermissionRule,
+ ReportingDimensionValue,
+ ReportingMetricValue,
+ ReportingQuery,
+ ReportingResult,
+ ReportingRow,
+ ReportingSchema,
} from './admin-client'
// Admin client class (for advanced use / subclassing)
export { AdminClient } from './admin-client'
diff --git a/packages/admin-sdk/tests/store-settings.test.ts b/packages/admin-sdk/tests/store-settings.test.ts
index 3429ef7e10..57277f63e3 100644
--- a/packages/admin-sdk/tests/store-settings.test.ts
+++ b/packages/admin-sdk/tests/store-settings.test.ts
@@ -58,40 +58,60 @@ describe('me', () => {
})
})
-describe('dashboard', () => {
- describe('analytics', () => {
- it('GETs /dashboard/analytics', async () => {
+describe('reporting', () => {
+ describe('query', () => {
+ it('POSTs the query body to /reporting/query', async () => {
+ let body: Record<string, unknown> | null = null
+ server.use(
+ http.post(`${API_PREFIX}/reporting/query`, async ({ request }) => {
+ body = (await request.json()) as Record<string, unknown>
+ return HttpResponse.json({ meta: {}, totals: {}, rows: [] })
+ }),
+ )
+
+ await createTestClient().reporting.query({
+ metrics: ['gross_revenue'],
+ dimensions: [{ name: 'completed_at', grain: 'day' }],
+ compare: 'previous_period',
+ })
+
+ expect(body!.metrics).toEqual(['gross_revenue'])
+ expect(body!.compare).toBe('previous_period')
+ })
+ })
+
+ describe('schema', () => {
+ it('GETs /reporting/schema', async () => {
let hit = false
server.use(
- http.get(`${API_PREFIX}/dashboard/analytics`, () => {
+ http.get(`${API_PREFIX}/reporting/schema`, () => {
hit = true
- return HttpResponse.json({ orders_count: 0, total_sales: '0.0' })
+ return HttpResponse.json({ metrics: [], dimensions: [] })
}),
)
- await createTestClient().dashboard.analytics()
+ await createTestClient().reporting.schema()
expect(hit).toBe(true)
})
+ })
+})
- it('forwards optional query params', async () => {
+describe('dashboard', () => {
+ describe('operations', () => {
+ it('GETs /dashboard/operations and forwards optional params', async () => {
let url: URL | null = null
server.use(
- http.get(`${API_PREFIX}/dashboard/analytics`, ({ request }) => {
+ http.get(`${API_PREFIX}/dashboard/operations`, ({ request }) => {
url = new URL(request.url)
- return HttpResponse.json({ orders_count: 0, total_sales: '0.0' })
+ return HttpResponse.json({ orders_to_fulfill: 0 })
}),
)
- await createTestClient().dashboard.analytics({
- date_from: '2026-05-01',
- date_to: '2026-05-31',
- currency: 'EUR',
- })
+ await createTestClient().dashboard.operations({ channel_id: 'ch_1', low_stock_threshold: 3 })
- expect(url!.searchParams.get('date_from')).toBe('2026-05-01')
- expect(url!.searchParams.get('date_to')).toBe('2026-05-31')
- expect(url!.searchParams.get('currency')).toBe('EUR')
+ expect(url!.searchParams.get('channel_id')).toBe('ch_1')
+ expect(url!.searchParams.get('low_stock_threshold')).toBe('3')
})
})
})
diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.json
index 0f87af138a..1a0650b983 100644
--- a/packages/dashboard-core/src/locales/ar.json
+++ b/packages/dashboard-core/src/locales/ar.json
@@ -194,7 +194,8 @@
"selected": "تم تحديد {{count}}"
},
"channel_select": {
- "placeholder": "اختر قناة مبيعات"
+ "placeholder": "اختر قناة مبيعات",
+ "all_channels": "جميع القنوات"
},
"command_palette": {
"create": {
diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.json
index 44199827e8..a15b962865 100644
--- a/packages/dashboard-core/src/locales/de.json
+++ b/packages/dashboard-core/src/locales/de.json
@@ -194,7 +194,8 @@
"selected": "{{count}} ausgewählt"
},
"channel_select": {
- "placeholder": "Verkaufskanal auswählen"
+ "placeholder": "Verkaufskanal auswählen",
+ "all_channels": "Alle Kanäle"
},
"command_palette": {
"create": {
diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.json
index c7b811634d..bfff45224d 100644
--- a/packages/dashboard-core/src/locales/en.json
+++ b/packages/dashboard-core/src/locales/en.json
@@ -194,7 +194,8 @@
"selected": "{{count}} selected"
},
"channel_select": {
- "placeholder": "Select a sales channel"
+ "placeholder": "Select a sales channel",
+ "all_channels": "All channels"
},
"command_palette": {
"create": {
diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.json
index 3da9b6c313..6b6e59d356 100644
--- a/packages/dashboard-core/src/locales/fr.json
+++ b/packages/dashboard-core/src/locales/fr.json
@@ -194,7 +194,8 @@
"selected": "{{count}} sélectionné(s)"
},
"channel_select": {
- "placeholder": "Sélectionner un canal de vente"
+ "placeholder": "Sélectionner un canal de vente",
+ "all_channels": "Tous les canaux"
},
"command_palette": {
"create": {
diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.json
index 5bdbbdd5b0..6c275b59c2 100644
--- a/packages/dashboard-core/src/locales/pl.json
+++ b/packages/dashboard-core/src/locales/pl.json
@@ -195,7 +195,8 @@
"selected": "Wybrano: {{count}}"
},
"channel_select": {
- "placeholder": "Wybierz kanał sprzedaży"
+ "placeholder": "Wybierz kanał sprzedaży",
+ "all_channels": "Wszystkie kanały"
},
"command_palette": {
"create": {
diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.json
index 65d1b4ebd4..d6903aeb78 100644
--- a/packages/dashboard-core/src/locales/zh-CN.json
+++ b/packages/dashboard-core/src/locales/zh-CN.json
@@ -194,7 +194,8 @@
"selected": "已选择 {{count}} 项"
},
"channel_select": {
- "placeholder": "选择销售渠道"
+ "placeholder": "选择销售渠道",
+ "all_channels": "全部渠道"
},
"command_palette": {
"create": {
diff --git a/packages/dashboard-ui/src/spree/icons.ts b/packages/dashboard-ui/src/spree/icons.ts
index f5133efd16..c794855293 100644
--- a/packages/dashboard-ui/src/spree/icons.ts
+++ b/packages/dashboard-ui/src/spree/icons.ts
@@ -102,6 +102,7 @@ export {
OctagonXIcon,
PackageCheckIcon,
PackageIcon,
+ PackageXIcon,
PanelLeftIcon,
PaperclipIcon,
PauseIcon,
@@ -142,6 +143,8 @@ export {
TicketPercentIcon,
Trash2Icon,
TrashIcon,
+ TrendingDownIcon,
+ TrendingUpIcon,
TriangleAlertIcon,
TruckIcon,
Undo2Icon,
diff --git a/packages/dashboard/e2e/home-dashboard.spec.ts b/packages/dashboard/e2e/home-dashboard.spec.ts
new file mode 100644
index 0000000000..46a4993239
--- /dev/null
+++ b/packages/dashboard/e2e/home-dashboard.spec.ts
@@ -0,0 +1,76 @@
+import { expect, test } from '@playwright/test'
+import { login } from './helpers'
+
+const HOME_PATH = (storeId: string) => `/${storeId}`
+
+test.describe('home dashboard', () => {
+ test('renders KPI tiles with the comparison chart', async ({ page }) => {
+ const creds = await login(page)
+ await page.goto(HOME_PATH(creds.store_id))
+
+ await expect(page.getByRole('heading', { name: /^dashboard$/i })).toBeVisible({
+ timeout: 15_000,
+ })
+
+ // KPI metric tiles (buttons that switch the chart metric)
+ await expect(page.getByRole('button', { name: /total sales/i })).toBeVisible()
+ await expect(page.getByRole('button', { name: /total orders/i })).toBeVisible()
+ await expect(page.getByRole('button', { name: /avg order value/i })).toBeVisible()
+ await expect(page.getByRole('button', { name: /units sold/i })).toBeVisible()
+
+ // Comparison legend under the chart
+ await expect(page.getByText(/^this period$/i)).toBeVisible()
+ await expect(page.getByText(/^previous period$/i)).toBeVisible()
+
+ // Switching the active metric keeps the chart rendered
+ await page.getByRole('button', { name: /total orders/i }).click()
+ await expect(page.getByText(/^this period$/i)).toBeVisible()
+ })
+
+ test('renders the operations and rankings widgets', async ({ page }) => {
+ const creds = await login(page)
+ await page.goto(HOME_PATH(creds.store_id))
+
+ await expect(page.getByRole('heading', { name: /^dashboard$/i })).toBeVisible({
+ timeout: 15_000,
+ })
+
+ // Operations rows
+ await expect(page.getByText(/orders to fulfill/i)).toBeVisible()
+ await expect(page.getByText(/payments to collect/i)).toBeVisible()
+ await expect(page.getByText(/open returns/i)).toBeVisible()
+ await expect(page.getByText(/low stock variants/i)).toBeVisible()
+ await expect(page.getByText(/out of stock variants/i)).toBeVisible()
+
+ // Rankings card with customer/category tabs
+ await expect(page.getByText('Rankings', { exact: true })).toBeVisible()
+ await page.getByRole('button', { name: /^categories$/i }).click()
+ await page.getByRole('button', { name: /^customers$/i }).click()
+ })
+
+ test('scopes metrics by channel via the switcher', async ({ page }) => {
+ const creds = await login(page)
+ await page.goto(HOME_PATH(creds.store_id))
+
+ // Defaults to all channels
+ const switcher = page.getByRole('combobox').filter({ hasText: /all channels/i })
+ await expect(switcher).toBeVisible({ timeout: 15_000 })
+
+ await switcher.click()
+ await page.getByRole('option', { name: /wholesale/i }).click()
+
+ await expect(page.getByRole('combobox').filter({ hasText: /wholesale/i })).toBeVisible()
+ await expect(page.getByRole('button', { name: /total sales/i })).toBeVisible()
+ await expect(page.getByText(/orders to fulfill/i)).toBeVisible()
+ })
+
+ test('orders to fulfill links to the filtered orders list', async ({ page }) => {
+ const creds = await login(page)
+ await page.goto(HOME_PATH(creds.store_id))
+
+ await page.getByText(/orders to fulfill/i).click()
+
+ await expect(page).toHaveURL(/\/orders\?/, { timeout: 15_000 })
+ await expect(page.getByText(/fulfillment/i).first()).toBeVisible()
+ })
+})
diff --git a/packages/dashboard/src/components/spree/channel-select.tsx b/packages/dashboard/src/components/spree/channel-select.tsx
index d2c6c693bd..e38546845a 100644
--- a/packages/dashboard/src/components/spree/channel-select.tsx
+++ b/packages/dashboard/src/components/spree/channel-select.tsx
@@ -2,6 +2,9 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
import { useTranslation } from 'react-i18next'
import { useChannels } from '../../hooks/use-channels'
+/** Sentinel value for the unscoped "All channels" option — never sent to the API. */
+export const ALL_CHANNELS = 'all'
+
interface ChannelSelectProps {
/** ID for the trigger — paired with the parent `<FieldLabel htmlFor>`. */
id?: string
@@ -13,6 +16,10 @@ interface ChannelSelectProps {
onChange?: (channelId: string) => void
/** Placeholder shown when no channel is selected. */
placeholder?: string
+ /** Prepend an unscoped "All channels" option (value `ALL_CHANNELS`) — for report filters. */
+ allOption?: boolean
+ /** Extra classes for the trigger (e.g. a width constraint in toolbars). */
+ triggerClassName?: string
disabled?: boolean
}
@@ -30,31 +37,35 @@ export function ChannelSelect({
value,
onChange,
placeholder,
+ allOption,
+ triggerClassName,
disabled,
}: ChannelSelectProps) {
const { t } = useTranslation()
const { data } = useChannels()
const channels = data?.data ?? []
+ const allLabel = t('admin.components.channel_select.all_channels')
+ const fallback = allOption
+ ? allLabel
+ : (placeholder ?? t('admin.components.channel_select.placeholder'))
+
return (
<>
{name && <input type="hidden" name={name} value={value ?? ''} />}
<Select value={value ?? ''} onValueChange={(v) => onChange?.(v)} disabled={disabled}>
- <SelectTrigger id={id}>
+ <SelectTrigger id={id} className={triggerClassName}>
{/* Base UI's `<SelectValue>` defaults to rendering the raw `value`
(the prefixed ID). Use the children render-prop to look up the
name from our cached list so the trigger matches the items. */}
- <SelectValue
- placeholder={placeholder ?? t('admin.components.channel_select.placeholder')}
- >
+ <SelectValue placeholder={fallback}>
{(v) =>
- channels.find((c) => c.id === v)?.name ??
- placeholder ??
- t('admin.components.channel_select.placeholder')
+ v === ALL_CHANNELS ? allLabel : (channels.find((c) => c.id === v)?.name ?? fallback)
}
</SelectValue>
</SelectTrigger>
<SelectContent>
+ {allOption && <SelectItem value={ALL_CHANNELS}>{allLabel}</SelectItem>}
{channels.map((c) => (
<SelectItem key={c.id} value={c.id}>
{c.name}
diff --git a/packages/dashboard/src/hooks/use-reporting.ts b/packages/dashboard/src/hooks/use-reporting.ts
new file mode 100644
index 0000000000..5bebf8787e
--- /dev/null
+++ b/packages/dashboard/src/hooks/use-reporting.ts
@@ -0,0 +1,46 @@
+import type {
+ ReportingDimensionValue,
+ ReportingQuery,
+ ReportingResult,
+ ReportingRow,
+} from '@spree/admin-sdk'
+import { adminClient, useResourceKey } from '@spree/dashboard-core'
+import { useQuery } from '@tanstack/react-query'
+
+/**
+ * Runs a semantic reporting query (`POST /reporting/query`). The query object
+ * itself is part of the store-scoped cache key, so callers just describe what
+ * they want; identical queries share one request. Results stay fresh for 5
+ * minutes and the previous result is kept while a changed query refetches (no
+ * flicker when the merchant moves the date range or channel).
+ */
+export function useReportingQuery(query: ReportingQuery, options: { enabled?: boolean } = {}) {
+ return useQuery<ReportingResult>({
+ queryKey: useResourceKey('reporting', 'query', query),
+ queryFn: () => adminClient.reporting.query(query),
+ staleTime: 5 * 60 * 1000,
+ placeholderData: (previousData) => previousData,
+ enabled: options.enabled ?? true,
+ })
+}
+
+/**
+ * Narrows a row's dimension value to the hydrated display payload of a
+ * lookup-backed dimension. The runtime check replaces per-call-site casts.
+ */
+export function entityDimension(row: ReportingRow, name: string): ReportingDimensionValue {
+ const value = row.dimensions[name]
+ return typeof value === 'string' ? { id: null, label: value, meta: {} } : value
+}
+
+/** Narrows a row's dimension value to a raw bucket/status string. */
+export function rawDimension(row: ReportingRow, name: string): string {
+ const value = row.dimensions[name]
+ return typeof value === 'string' ? value : value.label
+}
+
+/** Reads a string field out of a hydrated dimension's `meta`, if present. */
+export function metaString(dimension: ReportingDimensionValue, key: string): string | undefined {
+ const value = dimension.meta?.[key]
+ return typeof value === 'string' ? value : undefined
+}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index bfe35590bb..a0c7008e4c 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -3169,22 +3169,65 @@
"columns": {
"price": "سعر",
"product": "منتج",
- "sold": "مُباع"
+ "sold": "مُباع",
+ "trend": "الاتجاه"
},
"metric_short": {
"avg_order_value": "AOV",
"orders": "طلبات",
- "sales": "مبيعات"
+ "sales": "مبيعات",
+ "units": "وحدات",
+ "customers": "عملاء"
},
"metrics": {
"avg_order_value": "متوسط ​​قيمة الطلب",
"orders": "إجمالي الطلبات",
- "sales": "إجمالي المبيعات"
+ "sales": "إجمالي المبيعات",
+ "units": "الوحدات المباعة",
+ "customers": "العملاء"
},
"subtitle": "نظرة عامة على أداء متجرك",
"title": "Dashboard",
"top_products": "Top Products",
- "top_products_description": "المنتجات الأكثر مبيعا في متجرك."
+ "top_products_description": "المنتجات الأكثر مبيعا في متجرك.",
+ "legend": {
+ "current": "الفترة الحالية",
+ "previous": "الفترة السابقة"
+ },
+ "growth": {
+ "new": "جديد",
+ "vs_previous": "مقارنة بالفترة السابقة"
+ },
+ "operations": {
+ "title": "العمليات",
+ "subtitle": "ما يتطلب انتباهك الآن.",
+ "orders_to_fulfill": "طلبات بانتظار الشحن",
+ "payments_to_collect": "مدفوعات مستحقة التحصيل",
+ "open_returns": "مرتجعات مفتوحة",
+ "low_stock_items": "متغيرات ذات مخزون منخفض",
+ "out_of_stock_items": "متغيرات نفد مخزونها"
+ },
+ "rankings": {
+ "title": "التصنيفات",
+ "subtitle": "الأفضل أداءً في الفترة المحددة.",
+ "tabs": {
+ "customers": "العملاء",
+ "categories": "الفئات"
+ },
+ "orders_count_zero": "لا طلبات",
+ "orders_count_one": "طلب واحد",
+ "orders_count_two": "طلبان",
+ "orders_count_few": "{{count}} طلبات",
+ "orders_count_many": "{{count}} طلبًا",
+ "orders_count_other": "{{count}} طلب",
+ "units_count_zero": "لا وحدات",
+ "units_count_one": "وحدة واحدة",
+ "units_count_two": "وحدتان",
+ "units_count_few": "{{count}} وحدات",
+ "units_count_many": "{{count}} وحدة",
+ "units_count_other": "{{count}} وحدة",
+ "empty": "لا توجد بيانات لهذه الفترة بعد."
+ }
},
"orders": {
"detail": {
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 8d20c5c4e8..8367857bb3 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -3152,22 +3152,57 @@
"columns": {
"price": "Preis",
"product": "Produkt",
- "sold": "Verkauft"
+ "sold": "Verkauft",
+ "trend": "Trend"
},
"metric_short": {
"avg_order_value": "Ø-Wert",
"orders": "Bestellungen",
- "sales": "Umsatz"
+ "sales": "Umsatz",
+ "units": "Stück",
+ "customers": "Kunden"
},
"metrics": {
"avg_order_value": "Ø Bestellwert",
"orders": "Bestellungen gesamt",
- "sales": "Gesamtumsatz"
+ "sales": "Gesamtumsatz",
+ "units": "Verkaufte Stück",
+ "customers": "Kunden"
},
"subtitle": "Überblick über die Leistung Ihres Shops",
"title": "Dashboard",
"top_products": "Top-Produkte",
- "top_products_description": "Meistverkaufte Produkte in Ihrem Shop."
+ "top_products_description": "Meistverkaufte Produkte in Ihrem Shop.",
+ "legend": {
+ "current": "Dieser Zeitraum",
+ "previous": "Vorheriger Zeitraum"
+ },
+ "growth": {
+ "new": "Neu",
+ "vs_previous": "vs. vorheriger Zeitraum"
+ },
+ "operations": {
+ "title": "Aufgaben",
+ "subtitle": "Was gerade Ihre Aufmerksamkeit braucht.",
+ "orders_to_fulfill": "Zu versendende Bestellungen",
+ "payments_to_collect": "Ausstehende Zahlungen",
+ "open_returns": "Offene Retouren",
+ "low_stock_items": "Varianten mit niedrigem Bestand",
+ "out_of_stock_items": "Nicht vorrätige Varianten"
+ },
+ "rankings": {
+ "title": "Rangliste",
+ "subtitle": "Top-Performer im ausgewählten Zeitraum.",
+ "tabs": {
+ "customers": "Kunden",
+ "categories": "Kategorien"
+ },
+ "orders_count_one": "{{count}} Bestellung",
+ "orders_count_other": "{{count}} Bestellungen",
+ "units_count_one": "{{count}} Stück",
+ "units_count_other": "{{count}} Stück",
+ "empty": "Noch keine Daten für diesen Zeitraum."
+ }
},
"orders": {
"detail": {
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 920177ff14..efaeee38ec 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -3152,22 +3152,57 @@
"columns": {
"price": "Price",
"product": "Product",
- "sold": "Sold"
+ "sold": "Sold",
+ "trend": "Trend"
},
"metric_short": {
"avg_order_value": "AOV",
"orders": "Orders",
- "sales": "Sales"
+ "sales": "Sales",
+ "units": "Units",
+ "customers": "Customers"
},
"metrics": {
"avg_order_value": "Avg Order Value",
"orders": "Total Orders",
- "sales": "Total Sales"
+ "sales": "Total Sales",
+ "units": "Units Sold",
+ "customers": "Customers"
},
"subtitle": "Overview of your store performance",
"title": "Dashboard",
"top_products": "Top Products",
- "top_products_description": "Best-selling products in your store."
+ "top_products_description": "Best-selling products in your store.",
+ "legend": {
+ "current": "This period",
+ "previous": "Previous period"
+ },
+ "growth": {
+ "new": "New",
+ "vs_previous": "vs previous period"
+ },
+ "operations": {
+ "title": "Operations",
+ "subtitle": "What needs your attention right now.",
+ "orders_to_fulfill": "Orders to fulfill",
+ "payments_to_collect": "Payments to collect",
+ "open_returns": "Open returns",
+ "low_stock_items": "Low stock variants",
+ "out_of_stock_items": "Out of stock variants"
+ },
+ "rankings": {
+ "title": "Rankings",
+ "subtitle": "Top performers in the selected period.",
+ "tabs": {
+ "customers": "Customers",
+ "categories": "Categories"
+ },
+ "orders_count_one": "{{count}} order",
+ "orders_count_other": "{{count}} orders",
+ "units_count_one": "{{count}} unit",
+ "units_count_other": "{{count}} units",
+ "empty": "No data for this period yet."
+ }
},
"orders": {
"detail": {
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 68e1f45045..1a7e8ba8f6 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -3152,22 +3152,57 @@
"columns": {
"price": "Prix",
"product": "Produit",
- "sold": "Vendu"
+ "sold": "Vendu",
+ "trend": "Tendance"
},
"metric_short": {
"avg_order_value": "Panier moy.",
"orders": "Commandes",
- "sales": "Ventes"
+ "sales": "Ventes",
+ "units": "Unités",
+ "customers": "Clients"
},
"metrics": {
"avg_order_value": "Panier moyen",
"orders": "Commandes totales",
- "sales": "Ventes totales"
+ "sales": "Ventes totales",
+ "units": "Unités vendues",
+ "customers": "Clients"
},
"subtitle": "Aperçu des performances de votre boutique",
"title": "Tableau de bord",
"top_products": "Meilleurs produits",
- "top_products_description": "Produits les plus vendus de votre boutique."
+ "top_products_description": "Produits les plus vendus de votre boutique.",
+ "legend": {
+ "current": "Période actuelle",
+ "previous": "Période précédente"
+ },
+ "growth": {
+ "new": "Nouveau",
+ "vs_previous": "vs période précédente"
+ },
+ "operations": {
+ "title": "Opérations",
+ "subtitle": "Ce qui demande votre attention en ce moment.",
+ "orders_to_fulfill": "Commandes à expédier",
+ "payments_to_collect": "Paiements à encaisser",
+ "open_returns": "Retours ouverts",
+ "low_stock_items": "Variantes en stock faible",
+ "out_of_stock_items": "Variantes en rupture de stock"
+ },
+ "rankings": {
+ "title": "Classements",
+ "subtitle": "Meilleures performances sur la période sélectionnée.",
+ "tabs": {
+ "customers": "Clients",
+ "categories": "Catégories"
+ },
+ "orders_count_one": "{{count}} commande",
+ "orders_count_other": "{{count}} commandes",
+ "units_count_one": "{{count}} unité",
+ "units_count_other": "{{count}} unités",
+ "empty": "Pas encore de données pour cette période."
+ }
},
"orders": {
"detail": {
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 8976daf511..bb51f67e18 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -3184,22 +3184,61 @@
"columns": {
"price": "Cena",
"product": "Produkt",
- "sold": "Sprzedano"
+ "sold": "Sprzedano",
+ "trend": "Trend"
},
"metric_short": {
"avg_order_value": "Śr. wart.",
"orders": "Zamówienia",
- "sales": "Sprzedaż"
+ "sales": "Sprzedaż",
+ "units": "Sztuki",
+ "customers": "Klienci"
},
"metrics": {
"avg_order_value": "Śr. wartość zamówienia",
"orders": "Łączna liczba zamówień",
- "sales": "Łączna sprzedaż"
+ "sales": "Łączna sprzedaż",
+ "units": "Sprzedane sztuki",
+ "customers": "Klienci"
},
"subtitle": "Przegląd wyników Twojego sklepu",
"title": "Pulpit",
"top_products": "Najlepsze produkty",
- "top_products_description": "Najlepiej sprzedające się produkty w Twoim sklepie."
+ "top_products_description": "Najlepiej sprzedające się produkty w Twoim sklepie.",
+ "legend": {
+ "current": "Bieżący okres",
+ "previous": "Poprzedni okres"
+ },
+ "growth": {
+ "new": "Nowość",
+ "vs_previous": "względem poprzedniego okresu"
+ },
+ "operations": {
+ "title": "Operacje",
+ "subtitle": "Co teraz wymaga Twojej uwagi.",
+ "orders_to_fulfill": "Zamówienia do wysłania",
+ "payments_to_collect": "Płatności do pobrania",
+ "open_returns": "Otwarte zwroty",
+ "low_stock_items": "Warianty z niskim stanem magazynowym",
+ "out_of_stock_items": "Warianty niedostępne"
+ },
+ "rankings": {
+ "title": "Rankingi",
+ "subtitle": "Najlepsze wyniki w wybranym okresie.",
+ "tabs": {
+ "customers": "Klienci",
+ "categories": "Kategorie"
+ },
+ "orders_count_one": "{{count}} zamówienie",
+ "orders_count_few": "{{count}} zamówienia",
+ "orders_count_many": "{{count}} zamówień",
+ "orders_count_other": "{{count}} zamówienia",
+ "units_count_one": "{{count}} sztuka",
+ "units_count_few": "{{count}} sztuki",
+ "units_count_many": "{{count}} sztuk",
+ "units_count_other": "{{count}} sztuki",
+ "empty": "Brak danych dla tego okresu."
+ }
},
"orders": {
"detail": {
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 0a6a32321b..c7e4aed140 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -3144,22 +3144,55 @@
"columns": {
"price": "价格",
"product": "商品",
- "sold": "已售"
+ "sold": "已售",
+ "trend": "趋势"
},
"metric_short": {
"avg_order_value": "客单价",
"orders": "订单数",
- "sales": "销售额"
+ "sales": "销售额",
+ "units": "件数",
+ "customers": "客户"
},
"metrics": {
"avg_order_value": "平均订单金额",
"orders": "总订单数",
- "sales": "总销售额"
+ "sales": "总销售额",
+ "units": "已售件数",
+ "customers": "客户数"
},
"subtitle": "您的店铺业绩概览",
"title": "仪表盘",
"top_products": "热销商品",
- "top_products_description": "您店铺中最畅销的商品。"
+ "top_products_description": "您店铺中最畅销的商品。",
+ "legend": {
+ "current": "本期",
+ "previous": "上一期"
+ },
+ "growth": {
+ "new": "新增",
+ "vs_previous": "对比上一期"
+ },
+ "operations": {
+ "title": "运营事项",
+ "subtitle": "当前需要您处理的事项。",
+ "orders_to_fulfill": "待发货订单",
+ "payments_to_collect": "待收款订单",
+ "open_returns": "未处理退货",
+ "low_stock_items": "低库存款式",
+ "out_of_stock_items": "缺货款式"
+ },
+ "rankings": {
+ "title": "排行榜",
+ "subtitle": "所选时间段内表现最佳。",
+ "tabs": {
+ "customers": "客户",
+ "categories": "类目"
+ },
+ "orders_count_other": "{{count}} 笔订单",
+ "units_count_other": "{{count}} 件",
+ "empty": "该时间段暂无数据。"
+ }
},
"orders": {
"detail": {
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
index 3c48a08a3f..2637331afe 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
@@ -1,6 +1,12 @@
-import type { DashboardAnalytics } from '@spree/admin-sdk'
-import { adminClient } from '@spree/dashboard-core'
+import type {
+ DashboardOperations,
+ ReportingDimensionValue,
+ ReportingQuery,
+ ReportingResult,
+} from '@spree/admin-sdk'
+import { adminClient, Can, Subject, usePermissions } from '@spree/dashboard-core'
import {
+ Badge,
Card,
CardContent,
CardDescription,
@@ -13,100 +19,217 @@ import {
type DateRange,
DateRangePicker,
Skeleton,
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
Thumbnail,
} from '@spree/dashboard-ui'
-import { PackageIcon } from '@spree/dashboard-ui/icons'
+import {
+ ChevronRightIcon,
+ CreditCardIcon,
+ MinusIcon,
+ PackageXIcon,
+ RotateCcwIcon,
+ TrendingDownIcon,
+ TrendingUpIcon,
+ TriangleAlertIcon,
+ TruckIcon,
+} from '@spree/dashboard-ui/icons'
import { useQuery } from '@tanstack/react-query'
import { createFileRoute, Link } from '@tanstack/react-router'
import { subDays } from 'date-fns'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { Bar, BarChart, CartesianGrid, XAxis } from 'recharts'
+import { Bar, CartesianGrid, ComposedChart, Line, XAxis } from 'recharts'
+import { ALL_CHANNELS, ChannelSelect } from '../../../components/spree/channel-select'
+import {
+ entityDimension,
+ metaString,
+ rawDimension,
+ useReportingQuery,
+} from '../../../hooks/use-reporting'
export const Route = createFileRoute('/_authenticated/$storeId/')({
component: DashboardPage,
})
-type ChartMetric = 'sales' | 'orders' | 'avg_order_value'
+// UI metric keys (stable i18n keys) → registered reporting metric names.
+const CHART_METRICS = {
+ sales: 'gross_revenue',
+ orders: 'orders_count',
+ avg_order_value: 'aov',
+ units: 'units_sold',
+ customers: 'customers_count',
+} as const
-const CHART_METRICS: ChartMetric[] = ['sales', 'orders', 'avg_order_value']
+type ChartMetric = keyof typeof CHART_METRICS
function DashboardPage() {
const { t } = useTranslation()
+ const { permissions } = usePermissions()
const [dateRange, setDateRange] = useState<DateRange>({
from: subDays(new Date(), 30),
to: new Date(),
})
+ const [channelId, setChannelId] = useState<string>(ALL_CHANNELS)
+
+ // Mirror the server's member-level authorization (Query#required_subjects):
+ // widgets whose dimensions the role cannot read are hidden instead of
+ // rendering 403-fed skeletons. UX only — the API enforces regardless.
+ const rankingTabs: RankingTab[] = [
+ ...(permissions.can('read', Subject.Customer) ? (['customers'] as const) : []),
+ ...(permissions.can('read', Subject.Category) ? (['categories'] as const) : []),
+ ]
+
+ const channelParam = channelId === ALL_CHANNELS ? undefined : channelId
+ // Shared by every widget query — the switcher and date range scope the whole screen.
+ const scope: Pick<ReportingQuery, 'time_range' | 'filters'> = {
+ time_range: { since: dateRange.from.toISOString(), until: dateRange.to.toISOString() },
+ ...(channelParam
+ ? { filters: [{ dimension: 'channel', op: 'eq' as const, value: channelParam }] }
+ : {}),
+ }
+
+ const { data: overview } = useReportingQuery({
+ metrics: Object.values(CHART_METRICS),
+ dimensions: [{ name: 'completed_at', grain: 'day' }],
+ compare: 'previous_period',
+ ...scope,
+ })
- const { data } = useQuery({
- queryKey: ['dashboard', 'analytics', dateRange.from.toISOString(), dateRange.to.toISOString()],
- queryFn: () =>
- adminClient.dashboard.analytics({
- date_from: dateRange.from.toISOString(),
- date_to: dateRange.to.toISOString(),
- }),
+ const { data: operations } = useQuery({
+ queryKey: ['dashboard', 'operations', channelId],
+ queryFn: () => adminClient.dashboard.operations({ channel_id: channelParam }),
staleTime: 5 * 60 * 1000,
placeholderData: (previousData) => previousData,
})
- if (!data) {
+ if (!overview) {
return <DashboardSkeleton />
}
return (
<div className="flex flex-col gap-6">
- <div className="flex items-center justify-between">
+ <div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold">{t('admin.pages.home.title')}</h1>
<p className="text-muted-foreground">{t('admin.pages.home.subtitle')}</p>
</div>
- <DateRangePicker value={dateRange} onChange={setDateRange} />
+ <div className="flex items-center gap-2">
+ {/* Scopes order-derived metrics to one channel; stock counts stay store-wide. */}
+ <ChannelSelect
+ allOption
+ triggerClassName="min-w-40"
+ value={channelId}
+ onChange={setChannelId}
+ />
+ <DateRangePicker value={dateRange} onChange={setDateRange} />
+ </div>
+ </div>
+ <AnalyticsChart data={overview} />
+ <div className="grid gap-6 lg:grid-cols-5">
+ <OperationsCard
+ data={operations}
+ className={rankingTabs.length > 0 ? 'lg:col-span-2' : 'lg:col-span-5'}
+ />
+ {rankingTabs.length > 0 && <RankingsCard scope={scope} tabs={rankingTabs} />}
</div>
- <AnalyticsChart data={data} />
- <TopProducts products={data.top_products} />
+ <Can I="read" a={Subject.Product}>
+ <TopProducts scope={scope} />
+ </Can>
</div>
)
}
-function AnalyticsChart({ data }: { data: DashboardAnalytics }) {
+/**
+ * Period-over-period delta indicator: green/red trend arrow + percentage, a
+ * neutral dash at 0, and a "New" badge when there is no previous-period
+ * baseline (`growth === null`).
+ */
+function GrowthBadge({ growth }: { growth: number | null | undefined }) {
+ const { t } = useTranslation()
+
+ if (growth === null || growth === undefined) {
+ return (
+ <Badge variant="secondary" title={t('admin.pages.home.growth.vs_previous')}>
+ {t('admin.pages.home.growth.new')}
+ </Badge>
+ )
+ }
+
+ const formatted = `${growth > 0 ? '+' : ''}${growth.toLocaleString()}%`
+
+ if (growth === 0) {
+ return (
+ <span
+ className="inline-flex items-center gap-0.5 text-xs font-medium text-muted-foreground"
+ title={t('admin.pages.home.growth.vs_previous')}
+ >
+ <MinusIcon className="size-3" />
+ {formatted}
+ </span>
+ )
+ }
+
+ return (
+ <span
+ className={`inline-flex items-center gap-0.5 text-xs font-medium ${
+ growth > 0 ? 'text-green-700 dark:text-green-400' : 'text-destructive'
+ }`}
+ title={t('admin.pages.home.growth.vs_previous')}
+ >
+ {growth > 0 ? <TrendingUpIcon className="size-3" /> : <TrendingDownIcon className="size-3" />}
+ {formatted}
+ </span>
+ )
+}
+
+function AnalyticsChart({ data }: { data: ReportingResult }) {
const { t, i18n } = useTranslation()
const locale = i18n.language
const [activeMetric, setActiveMetric] = useState<ChartMetric>('sales')
- const summaryValues: Record<ChartMetric, string> = {
- sales: data.summary.display_sales_total,
- orders: data.summary.orders_count.toLocaleString(),
- avg_order_value: data.summary.display_avg_order_value,
+ const totalFor = (uiKey: ChartMetric) => data.totals[CHART_METRICS[uiKey]]
+ const displayFor = (uiKey: ChartMetric) => {
+ const total = totalFor(uiKey)
+ return total?.display ?? (total?.value ?? 0).toLocaleString()
}
+ // One reporting query feeds both series: `value` is the current period,
+ // `previous` the aligned bucket from the comparison period.
+ const chartData = data.rows.map((row) => ({
+ date: rawDimension(row, 'completed_at'),
+ current: row.metrics[CHART_METRICS[activeMetric]]?.value ?? 0,
+ previous: row.metrics[CHART_METRICS[activeMetric]]?.previous ?? 0,
+ }))
+
const chartConfig: ChartConfig = {
- [activeMetric]: {
+ current: {
label: t(`admin.pages.home.metric_short.${activeMetric}`),
color: 'var(--chart-2)',
},
+ previous: {
+ label: t('admin.pages.home.legend.previous'),
+ color: 'var(--muted-foreground)',
+ },
}
+ const formatDay = (value: string) =>
+ new Date(value).toLocaleDateString(locale, { month: 'short', day: 'numeric' })
+
return (
<Card>
- <CardHeader className="flex h-auto flex-row border-b p-0 gap-0">
- {CHART_METRICS.map((metric) => (
+ <CardHeader className="grid h-auto grid-cols-2 gap-0 border-b p-0 sm:grid-cols-3 lg:grid-cols-5">
+ {(Object.keys(CHART_METRICS) as ChartMetric[]).map((metric) => (
<button
key={metric}
type="button"
onClick={() => setActiveMetric(metric)}
className="relative flex min-w-0 flex-1 flex-col justify-center gap-1 border-l px-3 py-3 text-left transition-colors first:border-l-0 hover:bg-accent/40 sm:px-6 sm:py-4"
>
- <span className="truncate text-xs text-muted-foreground">
+ <span className="text-xs text-muted-foreground">
{t(`admin.pages.home.metrics.${metric}`)}
</span>
- <span className="truncate text-base font-bold leading-none sm:text-lg">
- {summaryValues[metric]}
+ <span className="flex items-center gap-2">
+ <span className="text-lg font-bold leading-none">{displayFor(metric)}</span>
+ <GrowthBadge growth={totalFor(metric)?.growth} />
</span>
{activeMetric === metric && (
<span className="absolute inset-x-0 bottom-0 h-0.5 bg-primary" />
@@ -116,7 +239,7 @@ function AnalyticsChart({ data }: { data: DashboardAnalytics }) {
</CardHeader>
<CardContent className="px-2 pt-4 sm:px-6 sm:pt-6">
<ChartContainer config={chartConfig} className="aspect-auto h-[250px] w-full">
- <BarChart data={data.chart_data}>
+ <ComposedChart data={chartData}>
<CartesianGrid vertical={false} />
<XAxis
dataKey="date"
@@ -124,10 +247,7 @@ function AnalyticsChart({ data }: { data: DashboardAnalytics }) {
axisLine={false}
tickMargin={8}
minTickGap={32}
- tickFormatter={(value: string) => {
- const date = new Date(value)
- return date.toLocaleDateString(locale, { month: 'short', day: 'numeric' })
- }}
+ tickFormatter={formatDay}
/>
<ChartTooltip
cursor={{ fill: 'rgba(0, 0, 0, 0.04)' }}
@@ -144,22 +264,361 @@ function AnalyticsChart({ data }: { data: DashboardAnalytics }) {
}
/>
<Bar
- dataKey={activeMetric}
- fill={`var(--color-${activeMetric})`}
+ dataKey="current"
+ fill="var(--color-current)"
opacity={0.8}
activeBar={{ opacity: 1 }}
radius={[4, 4, 0, 0]}
/>
- </BarChart>
+ <Line
+ dataKey="previous"
+ stroke="var(--color-previous)"
+ strokeWidth={2}
+ strokeDasharray="4 4"
+ strokeOpacity={0.7}
+ dot={false}
+ type="monotone"
+ />
+ </ComposedChart>
</ChartContainer>
+ <div className="flex items-center justify-center gap-6 pb-2 pt-3 text-xs text-muted-foreground">
+ <span className="inline-flex items-center gap-1.5">
+ <span className="size-2.5 rounded-[2px]" style={{ background: 'var(--chart-2)' }} />
+ {t('admin.pages.home.legend.current')}
+ </span>
+ <span className="inline-flex items-center gap-1.5">
+ <span
+ className="h-0 w-4 border-t-2 border-dashed"
+ style={{ borderColor: 'var(--muted-foreground)' }}
+ />
+ {t('admin.pages.home.legend.previous')}
+ </span>
+ </div>
</CardContent>
</Card>
)
}
-function TopProducts({ products }: { products: DashboardAnalytics['top_products'] }) {
+const OPERATIONS_ROW_CLASS = 'flex items-center gap-3 border-b px-4 py-3 last:border-0'
+
+type OperationsFilter = { id: string; field: string; operator: string; value: string }
+
+const OPERATIONS_ROWS: Array<{
+ key: keyof Omit<DashboardOperations, 'low_stock_threshold' | 'channel_id'>
+ icon: typeof TruckIcon
+ link?: { to: '/$storeId/orders' | '/$storeId/products'; filters: OperationsFilter[] }
+}> = [
+ {
+ key: 'orders_to_fulfill',
+ icon: TruckIcon,
+ link: {
+ to: '/$storeId/orders',
+ filters: [
+ // Mirrors the `ready_to_ship` scope backing the count.
+ { id: 'home-fulfill', field: 'fulfillment_status', operator: 'eq', value: 'unfulfilled' },
+ ],
+ },
+ },
+ {
+ key: 'payments_to_collect',
+ icon: CreditCardIcon,
+ link: {
+ to: '/$storeId/orders',
+ filters: [
+ // Mirrors the payments_to_collect statuses backing the count.
+ {
+ id: 'home-collect',
+ field: 'payment_status',
+ operator: 'in',
+ value: 'none,authorized,partially_paid',
+ },
+ ],
+ },
+ },
+ { key: 'open_returns', icon: RotateCcwIcon },
+ { key: 'low_stock_items', icon: TriangleAlertIcon },
+ {
+ key: 'out_of_stock_items',
+ icon: PackageXIcon,
+ link: {
+ to: '/$storeId/products',
+ filters: [{ id: 'home-oos', field: 'in_stock', operator: 'eq', value: 'false' }],
+ },
+ },
+]
+
+function OperationsCard({
+ data,
+ className,
+}: {
+ data: DashboardOperations | undefined
+ className: string
+}) {
const { t } = useTranslation()
- if (products.length === 0) {
+ const { storeId } = Route.useParams()
+
+ return (
+ <Card className={className}>
+ <CardHeader>
+ <CardTitle>{t('admin.pages.home.operations.title')}</CardTitle>
+ <CardDescription>{t('admin.pages.home.operations.subtitle')}</CardDescription>
+ </CardHeader>
+ <CardContent className="p-0">
+ <div className="flex flex-col">
+ {OPERATIONS_ROWS.map(({ key, icon: Icon, link }) => {
+ const count = data?.[key]
+ const content = (
+ <>
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-md border bg-muted/50">
+ <Icon className="size-4 text-muted-foreground" />
+ </span>
+ <span className="flex-1 text-sm">{t(`admin.pages.home.operations.${key}`)}</span>
+ {count === undefined ? (
+ <Skeleton className="h-4 w-8" />
+ ) : (
+ <span
+ className={`text-sm font-semibold tabular-nums ${
+ count === 0 ? 'text-muted-foreground' : ''
+ }`}
+ >
+ {count.toLocaleString()}
+ </span>
+ )}
+ {link && <ChevronRightIcon className="size-4 text-muted-foreground" />}
+ </>
+ )
+
+ if (link) {
+ return (
+ <Link
+ key={key}
+ to={link.to}
+ params={{ storeId }}
+ search={{ filters: link.filters }}
+ className={`${OPERATIONS_ROW_CLASS} hover:bg-muted/25`}
+ >
+ {content}
+ </Link>
+ )
+ }
+
+ return (
+ <div key={key} className={OPERATIONS_ROW_CLASS}>
+ {content}
+ </div>
+ )
+ })}
+ </div>
+ </CardContent>
+ </Card>
+ )
+}
+
+type RankingTab = 'customers' | 'categories'
+
+// Each tab is one contract query; the revenue metric doubles as the share bar.
+const RANKING_QUERIES: Record<
+ RankingTab,
+ {
+ query: Omit<ReportingQuery, 'time_range' | 'filters'>
+ revenueMetric: string
+ countMetric: string
+ }
+> = {
+ customers: {
+ query: {
+ metrics: ['gross_revenue', 'orders_count'],
+ dimensions: ['customer'],
+ sort: '-gross_revenue',
+ limit: 5,
+ },
+ revenueMetric: 'gross_revenue',
+ countMetric: 'orders_count',
+ },
+ categories: {
+ query: {
+ metrics: ['net_revenue', 'units_sold'],
+ dimensions: ['category'],
+ sort: '-net_revenue',
+ limit: 5,
+ },
+ revenueMetric: 'net_revenue',
+ countMetric: 'units_sold',
+ },
+}
+
+function RankingsCard({
+ scope,
+ tabs,
+}: {
+ scope: Pick<ReportingQuery, 'time_range' | 'filters'>
+ /** Permission-filtered, non-empty — the parent hides the card otherwise. */
+ tabs: RankingTab[]
+}) {
+ const { t } = useTranslation()
+ const { storeId } = Route.useParams()
+ const [tab, setTab] = useState<RankingTab>(tabs[0])
+
+ const { query, revenueMetric, countMetric } = RANKING_QUERIES[tab]
+ const { data } = useReportingQuery({ ...query, ...scope })
+
+ const rows = data?.rows.map((row) => {
+ const dimension = entityDimension(row, tab === 'customers' ? 'customer' : 'category')
+ const amount = row.metrics[revenueMetric]
+ const count = row.metrics[countMetric]?.value ?? 0
+ return {
+ key: dimension.id ?? dimension.label,
+ dimension,
+ amount: amount?.value ?? 0,
+ display: amount?.display ?? String(amount?.value ?? 0),
+ meta:
+ tab === 'customers'
+ ? t('admin.pages.home.rankings.orders_count', { count })
+ : t('admin.pages.home.rankings.units_count', { count }),
+ }
+ })
+
+ const maxAmount = rows?.length ? Math.max(...rows.map((row) => row.amount)) : 0
+
+ return (
+ <Card className="lg:col-span-3">
+ <CardHeader className="flex flex-row items-start justify-between gap-4">
+ <div className="flex flex-col gap-1.5">
+ <CardTitle>{t('admin.pages.home.rankings.title')}</CardTitle>
+ <CardDescription>{t('admin.pages.home.rankings.subtitle')}</CardDescription>
+ </div>
+ <div className="flex rounded-lg border p-0.5">
+ {tabs.map((value) => (
+ <button
+ key={value}
+ type="button"
+ onClick={() => setTab(value)}
+ className={`rounded-md px-3 py-1 text-sm ${
+ tab === value ? 'bg-muted font-medium' : 'text-muted-foreground hover:bg-muted/50'
+ }`}
+ >
+ {t(`admin.pages.home.rankings.tabs.${value}`)}
+ </button>
+ ))}
+ </div>
+ </CardHeader>
+ <CardContent className="p-0">
+ {rows === undefined ? (
+ <RankingRowsSkeleton />
+ ) : rows.length === 0 ? (
+ <p className="px-4 pb-6 pt-2 text-sm text-muted-foreground">
+ {t('admin.pages.home.rankings.empty')}
+ </p>
+ ) : (
+ <div className="flex flex-col">
+ {rows.map((row, index) => (
+ <div key={`${tab}-${row.key}`} className="border-b px-4 py-3 last:border-0">
+ <div className="flex items-baseline justify-between gap-3">
+ <span className="flex min-w-0 items-baseline gap-2 text-sm">
+ <span className="w-5 shrink-0 text-muted-foreground tabular-nums">
+ {index + 1}.
+ </span>
+ <RankingName tab={tab} storeId={storeId} dimension={row.dimension} />
+ </span>
+ <span className="shrink-0 text-right">
+ <span className="block text-sm font-medium tabular-nums">{row.display}</span>
+ <span className="block text-xs text-muted-foreground">{row.meta}</span>
+ </span>
+ </div>
+ <div className="mt-2 h-1 w-full overflow-hidden rounded-full bg-muted">
+ <div
+ className="h-full rounded-full"
+ style={{
+ background: 'var(--chart-2)',
+ width: `${maxAmount > 0 ? Math.max((row.amount / maxAmount) * 100, 2) : 0}%`,
+ }}
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+function RankingName({
+ tab,
+ storeId,
+ dimension,
+}: {
+ tab: RankingTab
+ storeId: string
+ dimension: ReportingDimensionValue
+}) {
+ const email = metaString(dimension, 'email')
+ const label = (
+ <span className="min-w-0">
+ <span className="block truncate font-medium">{dimension.label}</span>
+ {email && email !== dimension.label && (
+ <span className="block truncate text-xs text-muted-foreground">{email}</span>
+ )}
+ </span>
+ )
+
+ if (!dimension.id) {
+ return label
+ }
+
+ if (tab === 'customers') {
+ return (
+ <Link
+ to="/$storeId/customers/$customerId"
+ params={{ storeId, customerId: dimension.id }}
+ className="min-w-0 hover:underline"
+ >
+ {label}
+ </Link>
+ )
+ }
+
+ return (
+ <Link
+ to="/$storeId/products/categories/$categoryId"
+ params={{ storeId, categoryId: dimension.id }}
+ className="min-w-0 hover:underline"
+ >
+ {label}
+ </Link>
+ )
+}
+
+function RankingRowsSkeleton() {
+ return (
+ <div className="flex flex-col">
+ {['rank-1', 'rank-2', 'rank-3', 'rank-4', 'rank-5'].map((key) => (
+ <div key={key} className="border-b px-4 py-3 last:border-0">
+ <div className="flex items-center justify-between gap-3">
+ <Skeleton className="h-4 w-40" />
+ <Skeleton className="h-4 w-16" />
+ </div>
+ <Skeleton className="mt-2 h-1 w-full rounded-full" />
+ </div>
+ ))}
+ </div>
+ )
+}
+
+function TopProducts({ scope }: { scope: Pick<ReportingQuery, 'time_range' | 'filters'> }) {
+ const { t } = useTranslation()
+ const { storeId } = Route.useParams()
+
+ const { data } = useReportingQuery({
+ metrics: ['net_revenue', 'units_sold'],
+ dimensions: ['product'],
+ compare: 'previous_period',
+ sort: '-net_revenue',
+ limit: 5,
+ ...scope,
+ })
+
+ if (!data || data.rows.length === 0) {
return null
}
@@ -170,42 +629,62 @@ function TopProducts({ products }: { products: DashboardAnalytics['top_products'
<CardDescription>{t('admin.pages.home.top_products_description')}</CardDescription>
</CardHeader>
<CardContent className="p-0">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>{t('admin.pages.home.columns.product')}</TableHead>
- <TableHead className="text-right">{t('admin.pages.home.columns.price')}</TableHead>
- <TableHead className="text-right">{t('admin.pages.home.columns.sold')}</TableHead>
- <TableHead className="text-right">{t('admin.fields.total.label')}</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {products.map((product) => (
- <TableRow key={product.id}>
- <TableCell>
- <Link
- to="/$storeId/products/$productId"
- params={(prev) => ({
- storeId: prev.storeId!,
- productId: product.id,
- })}
- className="flex items-center gap-3 hover:underline"
- >
- <Thumbnail src={product.image_url} fallback={<PackageIcon />} />
- <span className="font-medium">{product.name}</span>
- </Link>
- </TableCell>
- <TableCell className="text-right text-muted-foreground tabular-nums">
- {product.price ?? '-'}
- </TableCell>
- <TableCell className="text-right tabular-nums">{product.quantity}</TableCell>
- <TableCell className="text-right font-medium tabular-nums">
- {product.total}
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b text-left text-muted-foreground">
+ <th className="px-4 py-2 font-medium">{t('admin.pages.home.columns.product')}</th>
+ <th className="px-4 py-2 text-right font-medium">
+ {t('admin.pages.home.columns.price')}
+ </th>
+ <th className="px-4 py-2 text-right font-medium">
+ {t('admin.pages.home.columns.sold')}
+ </th>
+ <th className="px-4 py-2 text-right font-medium">{t('admin.fields.total.label')}</th>
+ <th className="px-4 py-2 text-right font-medium">
+ {t('admin.pages.home.columns.trend')}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {data.rows.map((row) => {
+ const product = entityDimension(row, 'product')
+ const productId = product.id
+ const revenue = row.metrics.net_revenue
+ const thumbnail = metaString(product, 'thumbnail_url') ?? null
+ const price = metaString(product, 'price')
+
+ return (
+ <tr key={productId ?? product.label} className="border-b last:border-0">
+ <td className="px-4 py-3">
+ {productId ? (
+ <Link
+ to="/$storeId/products/$productId"
+ params={{ storeId, productId }}
+ className="flex items-center gap-3 hover:underline"
+ >
+ <Thumbnail src={thumbnail} size="sm" />
+ <span className="font-medium">{product.label}</span>
+ </Link>
+ ) : (
+ <span className="flex items-center gap-3">
+ <Thumbnail src={thumbnail} size="sm" />
+ <span className="font-medium">{product.label}</span>
+ </span>
+ )}
+ </td>
+ <td className="px-4 py-3 text-right text-muted-foreground">{price ?? '-'}</td>
+ <td className="px-4 py-3 text-right">{row.metrics.units_sold?.value ?? 0}</td>
+ <td className="px-4 py-3 text-right font-medium">
+ {revenue?.display ?? revenue?.value}
+ </td>
+ <td className="px-4 py-3 text-right">
+ <GrowthBadge growth={revenue?.growth} />
+ </td>
+ </tr>
+ )
+ })}
+ </tbody>
+ </table>
</CardContent>
</Card>
)
@@ -220,11 +699,11 @@ function DashboardSkeleton() {
<p className="text-muted-foreground">{t('admin.pages.home.subtitle')}</p>
</div>
<Card>
- <CardHeader className="flex h-auto flex-col border-b p-0 sm:flex-row">
- {['stat-1', 'stat-2', 'stat-3'].map((key) => (
+ <CardHeader className="grid h-auto grid-cols-2 gap-0 border-b p-0 sm:grid-cols-3 lg:grid-cols-5">
+ {['stat-1', 'stat-2', 'stat-3', 'stat-4', 'stat-5'].map((key) => (
<div
key={key}
- className="flex flex-1 flex-col gap-2 px-6 py-4 sm:border-l sm:first:border-l-0"
+ className="flex flex-col gap-2 px-6 py-4 sm:border-l sm:first:border-l-0"
>
<Skeleton className="h-3 w-20" />
<Skeleton className="h-7 w-28" />
@@ -235,25 +714,34 @@ function DashboardSkeleton() {
<Skeleton className="h-[250px] w-full" />
</CardContent>
</Card>
- <Card>
- <CardHeader>
- <Skeleton className="h-5 w-32" />
- <Skeleton className="h-4 w-56" />
- </CardHeader>
- <CardContent className="p-0">
- <div className="flex flex-col">
- {['row-1', 'row-2', 'row-3', 'row-4', 'row-5'].map((key) => (
- <div key={key} className="flex items-center gap-3 border-b px-4 py-3 last:border-0">
- <Skeleton className="size-10 rounded-md" />
- <Skeleton className="h-4 w-32 flex-1" />
- <Skeleton className="h-4 w-16" />
- <Skeleton className="h-4 w-12" />
- <Skeleton className="h-4 w-20" />
- </div>
- ))}
- </div>
- </CardContent>
- </Card>
+ <div className="grid gap-6 lg:grid-cols-5">
+ <Card className="lg:col-span-2">
+ <CardHeader>
+ <Skeleton className="h-5 w-32" />
+ <Skeleton className="h-4 w-56" />
+ </CardHeader>
+ <CardContent className="p-0">
+ <div className="flex flex-col">
+ {['op-1', 'op-2', 'op-3', 'op-4', 'op-5'].map((key) => (
+ <div key={key} className="flex items-center gap-3 border-b px-4 py-3 last:border-0">
+ <Skeleton className="size-8 rounded-md" />
+ <Skeleton className="h-4 w-32 flex-1" />
+ <Skeleton className="h-4 w-8" />
+ </div>
+ ))}
+ </div>
+ </CardContent>
+ </Card>
+ <Card className="lg:col-span-3">
+ <CardHeader>
+ <Skeleton className="h-5 w-32" />
+ <Skeleton className="h-4 w-56" />
+ </CardHeader>
+ <CardContent className="p-0">
+ <RankingRowsSkeleton />
+ </CardContent>
+ </Card>
+ </div>
</div>
)
}
diff --git a/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb
index 54abe71eee..4c0b8637f9 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,20 +2,19 @@ module Spree
module Api
module V3
module Admin
+ # Point-in-time operational counts for the dashboard home. Time-series
+ # analytics live in the semantic reporting endpoint (ReportingController).
class DashboardController < Admin::BaseController
scoped_resource :dashboard
- # GET /api/v3/admin/dashboard/analytics
- def analytics
- date_from = (params[:date_from] || 30.days.ago).to_time.beginning_of_day
- date_to = (params[:date_to] || Time.current).to_time.end_of_day
- currency = params[:currency] || current_store.default_currency
+ # GET /api/v3/admin/dashboard/operations
+ def operations
+ threshold = params.fetch(:low_stock_threshold, DashboardOperationsSerializer::DEFAULT_LOW_STOCK_THRESHOLD)
- serializer = DashboardAnalyticsSerializer.new(
+ serializer = DashboardOperationsSerializer.new(
store: current_store,
- currency: currency,
- time_range: date_from..date_to,
- params: serializer_params
+ channel: requested_channel,
+ low_stock_threshold: threshold.to_i.clamp(1, 1000)
)
render json: serializer.to_h
@@ -27,15 +26,11 @@ module Spree
'read'
end
- def serializer_params
- {
- store: current_store,
- locale: current_locale,
- currency: current_currency,
- user: current_user,
- includes: [],
- expand: []
- }
+ # Optional channel scoping — omitted means all channels.
+ def requested_channel
+ return if params[:channel_id].blank?
+
+ current_store.channels.find_by_prefix_id!(params[:channel_id])
end
end
end
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
new file mode 100644
index 0000000000..b01d0a2227
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/reporting_controller.rb
@@ -0,0 +1,77 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # The semantic reporting surface (docs/plans/6.0-analytics-semantic-layer.md):
+ # one query endpoint compiled against the Spree.reporting registry, plus
+ # registry introspection for pickers and agent tool schemas.
+ class ReportingController < Admin::BaseController
+ scoped_resource :reports
+
+ rescue_from Spree::Reporting::UnknownMember, Spree::Reporting::InvalidQuery, with: :render_invalid_query
+
+ QUERY_KEYS = %w[metrics dimensions filters time_range compare sort limit currency].freeze
+
+ # POST /api/v3/admin/reporting/query
+ def query
+ reporting_query = Spree::Reporting::Query.new(store: current_store, params: query_params)
+ authorize_reporting_members!(reporting_query)
+ return if performed?
+
+ result = reporting_query.execute
+
+ render json: ReportingResultSerializer.new(
+ result,
+ store: current_store,
+ params: serializer_params
+ ).to_h
+ end
+
+ # GET /api/v3/admin/reporting/schema
+ def schema
+ render json: Spree.reporting.schema
+ end
+
+ private
+
+ def action_kind
+ 'read'
+ end
+
+ # The contract owns shape validation (registry allowlist, loud
+ # rejection of unknown members) — nothing here is mass-assigned to a
+ # model, so strong-params filtering would only duplicate it.
+ def query_params
+ params.to_unsafe_h.slice(*QUERY_KEYS)
+ end
+
+ # Both credential types are authorized per referenced member:
+ # JWT admins via CanCanCan (`required_subjects`), secret keys via
+ # their scopes (`required_key_scopes` on top of the `read_reports`
+ # endpoint gate) — a key without `read_products` cannot query the
+ # product dimension any more than a limited staff role can.
+ def authorize_reporting_members!(reporting_query)
+ if current_api_key.present?
+ missing = reporting_query.required_key_scopes.reject { |scope| current_api_key.has_scope?(scope) }
+ return if missing.empty?
+
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:access_denied],
+ message: "API key lacks scope: #{missing.join(', ')}",
+ status: :forbidden,
+ details: { required_scopes: missing }
+ )
+ else
+ authorize!(:read, :reports)
+ reporting_query.required_subjects.each { |subject| authorize!(:read, subject) }
+ end
+ end
+
+ def render_invalid_query(error)
+ render_error(code: 'invalid_reporting_query', message: error.message, status: :unprocessable_content)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/dashboard_analytics_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/dashboard_analytics_serializer.rb
deleted file mode 100644
index cc2fa205e2..0000000000
--- a/spree/api/app/serializers/spree/api/v3/admin/dashboard_analytics_serializer.rb
+++ /dev/null
@@ -1,143 +0,0 @@
-module Spree
- module Api
- module V3
- module Admin
- class DashboardAnalyticsSerializer
- attr_reader :store, :currency, :time_range, :params
-
- def initialize(store:, currency:, time_range:, params: {})
- @store = store
- @currency = currency
- @time_range = time_range
- @params = params
- end
-
- def to_h
- {
- currency: currency,
- date_from: time_range.first.iso8601,
- date_to: time_range.last.iso8601,
- summary: summary,
- chart_data: chart_data,
- top_products: top_products
- }
- end
-
- private
-
- def orders
- @orders ||= store.orders.complete.where(currency: currency, completed_at: time_range)
- end
-
- def prev_orders
- @prev_orders ||= store.orders.complete.where(currency: currency, completed_at: previous_time_range)
- end
-
- def previous_time_range
- duration = time_range.last - time_range.first
- (time_range.first - duration)..(time_range.last - duration)
- end
-
- # ---- Summary ----
-
- def summary
- sales = sales_total
- count = orders_count
- avg = count > 0 ? (sales / count).round(2) : 0.0
-
- prev_sales = prev_orders.sum(:total).to_f
- prev_count = prev_orders.count
- prev_avg = prev_count > 0 ? (prev_sales / prev_count).round(2) : 0.0
-
- {
- sales_total: sales.round(2),
- display_sales_total: money(sales),
- sales_growth: growth_rate(sales, prev_sales),
- orders_count: count,
- orders_growth: growth_rate(count, prev_count),
- avg_order_value: avg,
- display_avg_order_value: money(avg),
- avg_order_value_growth: growth_rate(avg, prev_avg)
- }
- end
-
- def sales_total
- @sales_total ||= orders.sum(:total).to_f
- end
-
- def orders_count
- @orders_count ||= orders.count
- end
-
- # ---- Chart data ----
-
- def chart_data
- daily = orders
- .select("DATE(completed_at) AS day, SUM(total) AS day_total, COUNT(*) AS day_count")
- .group("DATE(completed_at)")
- .order("day")
- .index_by { |r| r.day.to_s }
-
- (time_range.first.to_date..time_range.last.to_date).map do |date|
- key = date.to_s
- row = daily[key]
- total = row&.day_total.to_f
- count = row&.day_count.to_i || 0
- {
- date: key,
- sales: total.round(2),
- orders: count,
- avg_order_value: count > 0 ? (total / count).round(2) : 0.0
- }
- end
- end
-
- # ---- Top products ----
-
- def top_products
- rows = Spree::LineItem
- .joins(:variant)
- .where(order: orders)
- .group('spree_variants.product_id')
- .order(Arel.sql('SUM(spree_line_items.quantity * spree_line_items.price) DESC'))
- .limit(5)
- .pluck(Arel.sql('spree_variants.product_id, SUM(spree_line_items.quantity), SUM(spree_line_items.quantity * spree_line_items.price)'))
-
- product_ids = rows.map(&:first).compact
- return [] if product_ids.empty?
-
- products = store.products.with_deleted.includes(:primary_media).where(id: product_ids)
- product_serializer = Spree.api.admin_product_serializer
-
- rows.filter_map do |product_id, quantity, amount|
- product = products.find { |p| p.id == product_id }
- next unless product
-
- serialized = product_serializer.new(product, params: params).to_h
- {
- id: serialized['id'],
- name: serialized['name'],
- slug: serialized['slug'],
- image_url: serialized['thumbnail_url'],
- price: serialized.dig('price', 'display_amount'),
- quantity: quantity.to_i,
- total: money(amount)
- }
- end
- end
-
- # ---- Helpers ----
-
- def money(amount)
- Spree::Money.new(amount, currency: currency).to_s
- end
-
- def growth_rate(current, previous)
- return 0.0 if previous.zero?
- (((current - previous) / previous.to_f) * 100).round(1)
- end
- end
- end
- end
- end
-end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/dashboard_operations_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/dashboard_operations_serializer.rb
new file mode 100644
index 0000000000..82b4f595b0
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/dashboard_operations_serializer.rb
@@ -0,0 +1,81 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Builds the home dashboard operations payload: counts of things that
+ # need back-office attention right now (not scoped to a date range).
+ # A channel narrows the order-derived counts; stock counts stay
+ # store-wide since inventory is channel-agnostic.
+ class DashboardOperationsSerializer
+ DEFAULT_LOW_STOCK_THRESHOLD = 5
+
+ attr_reader :store, :channel, :low_stock_threshold
+
+ def initialize(store:, channel: nil, low_stock_threshold: DEFAULT_LOW_STOCK_THRESHOLD)
+ @store = store
+ @channel = channel
+ @low_stock_threshold = low_stock_threshold
+ end
+
+ def to_h
+ {
+ channel_id: channel&.prefixed_id,
+ low_stock_threshold: low_stock_threshold,
+ orders_to_fulfill: orders_to_fulfill,
+ payments_to_collect: payments_to_collect,
+ open_returns: open_returns,
+ low_stock_items: low_stock_items,
+ out_of_stock_items: out_of_stock_items
+ }
+ end
+
+ private
+
+ def actionable_orders
+ store.orders.complete.not_canceled.for_channel(channel)
+ end
+
+ def orders_to_fulfill
+ actionable_orders.ready_to_ship.count
+ end
+
+ # Placed orders still owed money: nothing collected yet, authorized but
+ # not captured, or only partially paid.
+ def payments_to_collect
+ actionable_orders.where(payment_status: %w[none authorized partially_paid]).count
+ end
+
+ def open_returns
+ store.returns
+ .joins(:order)
+ .where(status: %w[requested approved])
+ .merge(Spree::Order.for_channel(channel))
+ .count
+ end
+
+ def low_stock_items
+ tracked_stock_items
+ .where(count_on_hand: 1..low_stock_threshold)
+ .distinct
+ .count(:variant_id)
+ end
+
+ def out_of_stock_items
+ tracked_stock_items
+ .where(count_on_hand: ..0)
+ .distinct
+ .count(:variant_id)
+ end
+
+ # `store.stock_levels` walks products → variants, so paranoia default
+ # scopes already exclude deleted products/variants.
+ def tracked_stock_items
+ store.stock_levels
+ .with_active_stock_location
+ .where(Spree::Variant.table_name => { track_inventory: true })
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/reporting_result_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/reporting_result_serializer.rb
new file mode 100644
index 0000000000..67a0d9a61b
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/reporting_result_serializer.rb
@@ -0,0 +1,81 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Decorates a Spree::Reporting::Result for the wire: money display
+ # strings, ISO ranges, and dimension hydration — raw group keys become
+ # { id, label, meta } display payloads via each dimension's registered
+ # `hydrate` lambda, batched once per dimension across all rows.
+ class ReportingResultSerializer
+ attr_reader :result, :store, :params
+
+ def initialize(result, store:, params: {})
+ @result = result
+ @store = store
+ @params = params
+ end
+
+ def to_h
+ {
+ meta: result.meta.merge(
+ time_range: iso_range(result.meta[:time_range]),
+ previous_time_range: iso_range(result.meta[:previous_time_range])
+ ),
+ totals: result.totals.to_h { |name, payload| [name, metric_payload(name, payload)] },
+ rows: result.rows.map do |row|
+ {
+ dimensions: row[:dimensions].to_h { |name, raw| [name, dimension_value(name, raw)] },
+ metrics: row[:metrics].to_h { |name, payload| [name, metric_payload(name, payload)] }
+ }
+ end
+ }
+ end
+
+ private
+
+ def iso_range(range)
+ return unless range
+
+ { since: range.first.iso8601, until: range.last.iso8601 }
+ end
+
+ def metric_payload(name, payload)
+ output = payload.dup
+ output[:display] = money(payload[:value]) if Spree.reporting.metrics[name]&.money?
+ output
+ end
+
+ def money(amount)
+ Spree::Money.new(amount, currency: result.meta[:currency]).to_s
+ end
+
+ def dimension_value(name, raw)
+ return raw unless dimension_defs[name].hydrate
+
+ hydrated_dimensions[name][raw] || { id: nil, label: raw.to_s, meta: {} }
+ end
+
+ def dimension_defs
+ @dimension_defs ||= Hash.new { |cache, name| cache[name] = Spree.reporting.dimension!(name) }
+ end
+
+ # One batched `hydrate` call per hydrated dimension across all rows.
+ def hydrated_dimensions
+ @hydrated_dimensions ||= begin
+ keys = Hash.new { |h, k| h[k] = [] }
+ result.rows.each do |row|
+ row[:dimensions].each do |name, raw|
+ keys[name] << raw if dimension_defs[name].hydrate
+ end
+ end
+
+ keys.to_h do |name, raws|
+ [name, dimension_defs[name].hydrate.call(store, raws.uniq, params)]
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 0e06b4299b..86979c46d2 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -245,9 +245,15 @@ Spree::Core::Engine.add_routes do
post 'auth/password_resets', to: 'password_resets#create'
patch 'auth/password_resets/:id', to: 'password_resets#update'
- # Dashboard
+ # Semantic reporting (docs/plans/6.0-analytics-semantic-layer.md)
+ namespace :reporting do
+ post :query
+ get :schema
+ end
+
+ # Dashboard (point-in-time operational counts)
namespace :dashboard do
- get :analytics
+ get :operations
end
# 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.rb
index 0c083b0aa1..a25f41d9df 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,104 +7,76 @@ RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller do
before { request.headers.merge!(headers) }
- describe 'GET #analytics' do
- subject { get :analytics, as: :json }
+ describe 'GET #operations' do
+ subject { get :operations, as: :json }
- it 'returns ok' do
+ it 'returns all counters' do
subject
expect(response).to have_http_status(:ok)
- end
-
- it 'returns summary stats' do
- subject
- expect(json_response['summary']).to include(
- 'sales_total', 'display_sales_total', 'sales_growth',
- 'orders_count', 'orders_growth',
- 'avg_order_value', 'display_avg_order_value', 'avg_order_value_growth'
+ expect(json_response).to include(
+ 'low_stock_threshold', 'orders_to_fulfill', 'payments_to_collect',
+ 'open_returns', 'low_stock_items', 'out_of_stock_items'
)
end
- it 'returns chart_data as an array' do
- subject
- expect(json_response['chart_data']).to be_an(Array)
- expect(json_response['chart_data'].length).to eq(31) # default 30 days + today
- end
+ context 'with actionable orders' do
+ let!(:ready_order) { create(:order_ready_to_ship, store: store) }
+ let!(:balance_due_order) do
+ create(:completed_order_with_totals, store: store, payment_status: 'authorized', fulfillment_status: 'fulfilled')
+ end
- it 'returns chart_data entries with date, sales, orders, avg_order_value' do
- subject
- entry = json_response['chart_data'].first
- expect(entry.keys).to match_array(%w[date sales orders avg_order_value])
- end
+ it 'counts orders to fulfill and payments to collect' do
+ subject
+ expect(json_response['orders_to_fulfill']).to eq(1)
+ expect(json_response['payments_to_collect']).to eq(1)
+ end
- it 'returns top_products as an array' do
- subject
- expect(json_response['top_products']).to be_an(Array)
- end
+ it 'scopes order counts to the requested channel' do
+ channel = create(:channel, store: store)
+ create(:order_ready_to_ship, store: store, channel: channel)
- it 'returns currency and date range' do
- subject
- expect(json_response['currency']).to eq(store.default_currency)
- expect(json_response['date_from']).to be_present
- expect(json_response['date_to']).to be_present
+ get :operations, params: { channel_id: channel.prefixed_id }, as: :json
+ expect(json_response['channel_id']).to eq(channel.prefixed_id)
+ expect(json_response['orders_to_fulfill']).to eq(1)
+ expect(json_response['payments_to_collect']).to eq(0)
+ end
end
- context 'with completed orders' do
- let!(:order1) { create(:completed_order_with_totals, store: store, completed_at: 5.days.ago) }
- let!(:order2) { create(:completed_order_with_totals, store: store, completed_at: 2.days.ago) }
-
- it 'calculates sales total from completed orders' do
- subject
- expected_total = (order1.total + order2.total).to_f.round(2)
- expect(json_response['summary']['sales_total']).to eq(expected_total)
- end
+ context 'with an open return' do
+ let!(:open_return) { create(:return) }
- it 'counts orders' do
+ it 'counts requested and approved returns' do
subject
- expect(json_response['summary']['orders_count']).to eq(2)
+ expect(json_response['open_returns']).to eq(1)
end
+ end
- it 'calculates average order value' do
- subject
- expected_avg = ((order1.total + order2.total) / 2.0).round(2)
- expect(json_response['summary']['avg_order_value']).to eq(expected_avg)
- end
+ context 'with stock levels' do
+ let!(:low_stock_product) { create(:product, store: store) }
+ let!(:out_of_stock_product) { create(:product, store: store) }
- it 'includes orders in chart_data on their completed dates' do
- subject
- chart = json_response['chart_data']
- day_with_order = chart.find { |d| d['date'] == 5.days.ago.to_date.to_s }
- expect(day_with_order['orders']).to be >= 1
- expect(day_with_order['sales']).to be > 0
+ before do
+ low_stock_product.default_variant.stock_levels.first.update!(count_on_hand: 3)
end
- it 'returns top products from line items' do
+ it 'counts low stock and out of stock variants' do
subject
- expect(json_response['top_products'].length).to be >= 1
-
- top = json_response['top_products'].first
- expect(top).to include('id', 'name', 'slug', 'quantity', 'total')
- expect(top['id']).to start_with('prod_')
- expect(top['quantity']).to be > 0
+ expect(json_response['low_stock_items']).to eq(1)
+ expect(json_response['out_of_stock_items']).to eq(1)
end
- end
- context 'with custom date range' do
- it 'accepts date_from and date_to params' do
- get :analytics, params: { date_from: 7.days.ago.to_s, date_to: Time.current.to_s }, as: :json
- expect(response).to have_http_status(:ok)
- expect(json_response['chart_data'].length).to be_between(7, 8)
+ it 'respects the low_stock_threshold param' do
+ get :operations, params: { low_stock_threshold: 2 }, as: :json
+ expect(json_response['low_stock_threshold']).to eq(2)
+ expect(json_response['low_stock_items']).to eq(0)
end
- end
-
- context 'with growth rate calculation' do
- let!(:recent_order) { create(:completed_order_with_totals, store: store, completed_at: 5.days.ago) }
- let!(:older_order) { create(:completed_order_with_totals, store: store, completed_at: 35.days.ago) }
- it 'calculates growth rates compared to previous period' do
+ it 'ignores variants that do not track inventory' do
+ low_stock_product.default_variant.update!(track_inventory: false)
+ out_of_stock_product.default_variant.update!(track_inventory: false)
subject
- # Recent period has orders, previous period also has orders
- expect(json_response['summary']['sales_growth']).to be_a(Numeric)
- expect(json_response['summary']['orders_growth']).to be_a(Numeric)
+ expect(json_response['low_stock_items']).to eq(0)
+ expect(json_response['out_of_stock_items']).to eq(0)
end
end
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
new file mode 100644
index 0000000000..a31d1bbded
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/reporting_controller_spec.rb
@@ -0,0 +1,184 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::ReportingController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ before { request.headers.merge!(headers) }
+
+ describe 'POST #query' do
+ subject { post :query, params: query_params, as: :json }
+
+ let(:query_params) do
+ {
+ metrics: %w[gross_revenue orders_count aov],
+ dimensions: [{ name: 'completed_at', grain: 'day' }],
+ compare: 'previous_period'
+ }
+ end
+
+ it 'returns ok with totals, rows and meta' 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['rows'].length).to eq(31) # default 30 days + today
+ end
+
+ context 'with completed orders' do
+ let!(:order1) { create(:completed_order_with_totals, store: store, completed_at: 5.days.ago) }
+ let!(:order2) { create(:completed_order_with_totals, store: store, completed_at: 2.days.ago) }
+
+ it 'computes totals with money display strings and nil growth without baseline' do
+ subject
+ 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))
+ end
+
+ it 'hydrates product rows with prefixed ids, labels and meta' do
+ post :query, params: {
+ metrics: %w[net_revenue units_sold],
+ dimensions: %w[product],
+ sort: '-net_revenue',
+ limit: 5
+ }, as: :json
+
+ row = json_response['rows'].first
+ 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
+ end
+
+ it 'hydrates customer rows and ranks by revenue' do
+ post :query, params: {
+ metrics: %w[gross_revenue orders_count],
+ dimensions: %w[customer],
+ sort: '-gross_revenue',
+ limit: 5
+ }, as: :json
+
+ expect(json_response['rows'].length).to eq(2)
+ 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)
+ end
+
+ it 'filters by channel' do
+ channel = create(:channel, store: store)
+ create(:completed_order_with_totals, store: store, channel: channel, completed_at: 3.days.ago)
+
+ post :query, params: {
+ metrics: %w[orders_count],
+ filters: [{ dimension: 'channel', op: 'eq', value: channel.prefixed_id }]
+ }, as: :json
+
+ expect(json_response['totals']['orders_count']['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],
+ filters: [{ dimension: 'channel', op: 'eq', value: foreign_channel.prefixed_id }]
+ }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ context 'with an invalid query' do
+ it 'rejects unknown members with the standard v3 error shape' do
+ post :query, params: { metrics: %w[revenues] }, as: :json
+
+ 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')
+ end
+ end
+
+ context 'without authentication' do
+ let(:headers) { {} }
+
+ it 'returns unauthorized' do
+ subject
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+ end
+
+ describe 'secret key member scopes' do
+ let(:headers) { { 'x-spree-api-key' => reports_key.plaintext_token } }
+ 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
+ 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
+
+ expect(response).to have_http_status(:forbidden)
+ expect(json_response['error']['details']['required_scopes']).to eq(%w[read_products])
+ end
+
+ it 'allows members once the key carries their scope' 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
+ expect(response).to have_http_status(:ok)
+ end
+ end
+
+ describe 'member-level permissions' do
+ include_context 'API v3 Admin with custom permissions'
+
+ # Reporting + order data, but no product/category/customer keys.
+ 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
+ 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
+ expect(response).to have_http_status(:forbidden)
+
+ post :query, params: { metrics: %w[gross_revenue], 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],
+ filters: [{ dimension: 'product', op: 'eq', value: 'prod_x' }]
+ }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+
+ describe 'GET #schema' do
+ it 'returns the registry introspection payload' do
+ get :schema, as: :json
+
+ expect(response).to have_http_status(:ok)
+ metric_names = json_response['metrics'].map { |m| m['name'] }
+ expect(metric_names).to include('net_revenue', 'orders_count', 'aov')
+ dimension = json_response['dimensions'].find { |d| d['name'] == 'completed_at' }
+ expect(dimension['grains']).to include('day')
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb b/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb
index 4c8431ee58..9825d1cadc 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 do
let(:scopes) { ['read_dashboard'] }
it 'enforces the scope and allows the read' do
- get :analytics, as: :json
+ get :operations, as: :json
expect(response).to have_http_status(:ok)
end
end
@@ -197,7 +197,7 @@ RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller do
let(:scopes) { ['read_orders'] }
it 'denies rather than silently skipping the scope check' do
- get :analytics, as: :json
+ get :operations, as: :json
expect(response).to have_http_status(:forbidden)
body = JSON.parse(response.body)
@@ -214,7 +214,7 @@ RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller do
end
it 'passes the key gate (admin holds the full catalog)' do
- get :analytics, as: :json
+ get :operations, as: :json
expect(response).to have_http_status(:ok)
end
end
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/dashboard_analytics_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/dashboard_analytics_serializer_spec.rb
deleted file mode 100644
index b7612296f6..0000000000
--- a/spree/api/spec/serializers/spree/api/v3/admin/dashboard_analytics_serializer_spec.rb
+++ /dev/null
@@ -1,129 +0,0 @@
-require 'spec_helper'
-
-RSpec.describe Spree::Api::V3::Admin::DashboardAnalyticsSerializer do
- let(:store) { @default_store }
- let(:currency) { store.default_currency }
- let(:time_range) { 30.days.ago.beginning_of_day..Time.current.end_of_day }
- let(:params) do
- {
- store: store,
- locale: 'en',
- currency: currency,
- user: nil,
- includes: [],
- expand: []
- }
- end
-
- subject { described_class.new(store: store, currency: currency, time_range: time_range, params: params) }
-
- describe '#to_h' do
- let(:result) { subject.to_h }
-
- it 'returns currency and date range' do
- expect(result[:currency]).to eq(currency)
- expect(result[:date_from]).to be_present
- expect(result[:date_to]).to be_present
- end
-
- it 'returns summary with all expected keys' do
- expect(result[:summary]).to include(
- :sales_total, :display_sales_total, :sales_growth,
- :orders_count, :orders_growth,
- :avg_order_value, :display_avg_order_value, :avg_order_value_growth
- )
- end
-
- it 'returns chart_data covering the full date range' do
- expected_days = (time_range.first.to_date..time_range.last.to_date).count
- expect(result[:chart_data].length).to eq(expected_days)
- end
-
- it 'returns chart_data entries with correct keys' do
- entry = result[:chart_data].first
- expect(entry.keys).to match_array(%i[date sales orders avg_order_value])
- end
-
- it 'returns top_products as an array' do
- expect(result[:top_products]).to be_an(Array)
- end
-
- context 'with no orders' do
- it 'returns zero summary values' do
- expect(result[:summary][:sales_total]).to eq(0.0)
- expect(result[:summary][:orders_count]).to eq(0)
- expect(result[:summary][:avg_order_value]).to eq(0.0)
- expect(result[:summary][:sales_growth]).to eq(0.0)
- end
-
- it 'returns empty top_products' do
- expect(result[:top_products]).to eq([])
- end
-
- it 'returns zero values in chart_data' do
- result[:chart_data].each do |entry|
- expect(entry[:sales]).to eq(0.0)
- expect(entry[:orders]).to eq(0)
- expect(entry[:avg_order_value]).to eq(0.0)
- end
- end
- end
-
- context 'with completed orders' do
- let!(:order1) { create(:completed_order_with_totals, store: store, completed_at: 5.days.ago) }
- let!(:order2) { create(:completed_order_with_totals, store: store, completed_at: 2.days.ago) }
-
- it 'calculates sales total' do
- expected = (order1.total + order2.total).to_f.round(2)
- expect(result[:summary][:sales_total]).to eq(expected)
- end
-
- it 'counts orders' do
- expect(result[:summary][:orders_count]).to eq(2)
- end
-
- it 'calculates avg order value' do
- expected = ((order1.total + order2.total) / 2.0).round(2)
- expect(result[:summary][:avg_order_value]).to eq(expected)
- end
-
- it 'formats display values as money strings' do
- expect(result[:summary][:display_sales_total]).to include('$')
- expect(result[:summary][:display_avg_order_value]).to include('$')
- end
-
- it 'populates chart_data on order dates' do
- day = result[:chart_data].find { |d| d[:date] == 5.days.ago.to_date.to_s }
- expect(day[:orders]).to be >= 1
- expect(day[:sales]).to be > 0
- end
-
- it 'returns top products with serialized fields' do
- expect(result[:top_products].length).to be >= 1
- top = result[:top_products].first
- expect(top[:id]).to start_with('prod_').or be_present
- expect(top[:name]).to be_present
- expect(top[:quantity]).to be > 0
- expect(top[:total]).to include('$')
- end
- end
-
- context 'with growth rate calculation' do
- let!(:recent_order) { create(:completed_order_with_totals, store: store, completed_at: 5.days.ago) }
- let!(:older_order) { create(:completed_order_with_totals, store: store, completed_at: 35.days.ago) }
-
- it 'calculates non-zero growth rates when both periods have data' do
- expect(result[:summary][:sales_growth]).to be_a(Numeric)
- expect(result[:summary][:orders_growth]).to be_a(Numeric)
- end
- end
-
- context 'with custom 7-day range' do
- let(:time_range) { 7.days.ago.beginning_of_day..Time.current.end_of_day }
-
- it 'returns chart_data for 7-8 days' do
- expect(result[:chart_data].length).to be_between(7, 8)
- end
- end
- end
-end
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 3aaffa717b..01977a12ae 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -280,6 +280,8 @@ module Spree
scope :incomplete, -> { where(completed_at: nil) }
scope :canceled, -> { where(status: 'canceled') }
scope :not_canceled, -> { where.not(status: 'canceled') }
+ # Nil-tolerant channel filter for optional scoping (nil means all channels).
+ scope :for_channel, ->(channel) { channel ? where(channel_id: channel.id) : all }
scope :ready_to_ship, -> { where(fulfillment_status: %w[unfulfilled]) }
scope :partially_shipped, -> { where(fulfillment_status: %w[partial]) }
scope :not_shipped, -> { where(fulfillment_status: %w[unfulfilled partial]) }
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 36643ce19a..b642377e75 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -156,6 +156,7 @@ module Spree
has_many :carts, class_name: 'Spree::Cart', inverse_of: :store, dependent: :destroy
has_many :orders, class_name: 'Spree::Order'
has_many :order_groups, class_name: 'Spree::OrderGroup'
+ has_many :customers, through: :orders, source: :customer
has_many :line_items, through: :orders, class_name: 'Spree::LineItem'
has_many :digital_links, through: :line_items, class_name: 'Spree::DigitalLink'
has_many :fulfillments, through: :orders, class_name: 'Spree::Fulfillment'
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index 8560932d53..cacc95b05e 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -749,6 +749,18 @@ module Spree
Rails.application.config.spree.seller_authentication_strategies = value
end
+ # Semantic reporting registry — the queryable metric/dimension vocabulary.
+ # Not to be confused with +Spree.analytics+ (storefront event tracking).
+ #
+ # @return [Spree::Reporting::Registry]
+ def self.reporting
+ Rails.application.config.spree.reporting
+ end
+
+ def self.reporting=(value)
+ Rails.application.config.spree.reporting = value
+ end
+
def self.analytics
@analytics ||= AnalyticsConfig.new
end
@@ -895,6 +907,7 @@ require 'spree/money'
require 'spree/service_module'
require 'spree/workflow'
require 'spree/analytics'
+require 'spree/reporting'
require 'spree/events'
require 'spree/store_scope_guard'
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index d65fb925e8..272f5a8a4d 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -7,6 +7,9 @@ module Spree
# ability (staff / back-office authorization)
ability_class: 'Spree::Ability',
+ # reporting (see docs/plans/6.0-analytics-semantic-layer.md)
+ reporting_adapter: 'Spree::Reporting::Adapters::Live',
+
# storefront record access (ownership + guest tokens); the B2B seam —
# see Spree::Storefront::AccessPolicy
storefront_access_policy_class: 'Spree::Storefront::AccessPolicy',
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 4d011d0cbb..1024d4e26a 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -46,6 +46,7 @@ module Spree
:translatable_resources,
:taggable_types,
:custom_fields,
+ :reporting,
:analytics_events,
:analytics_event_handlers,
:integrations,
@@ -192,6 +193,14 @@ module Spree
app.config.spree.custom_fields.enabled_resources = []
end
+ # Seed the reporting vocabulary before app initializers so applications
+ # and extensions can register their own metrics/dimensions in
+ # config/initializers (see docs/plans/6.0-analytics-semantic-layer.md).
+ initializer 'spree.register.reporting', before: :load_config_initializers do |app|
+ app.config.spree.reporting = Spree::Reporting::Registry.new
+ Spree::Reporting::DefaultVocabulary.install(app.config.spree.reporting)
+ end
+
# We need to define promotions rules here so extensions and existing apps
# can add their custom classes on their initializer files
initializer 'spree.promo.environment' do |app|
diff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rb
index db240da364..e2f6508d27 100644
--- a/spree/core/lib/spree/core/permission_configuration.rb
+++ b/spree/core/lib/spree/core/permission_configuration.rb
@@ -485,6 +485,9 @@ module Spree
register_resource(:dashboard, group: :analytics, subjects: -> { [:dashboard] },
write: false, audiences: %i[seller])
+ # Semantic reporting (docs/plans/6.0-analytics-semantic-layer.md). Staff
+ # only until seller queries get a compiler-forced seller scope.
+ register_resource(:reports, group: :analytics, subjects: -> { [:reports] }, write: false)
end
# rubocop:enable Metrics/MethodLength
end
diff --git a/spree/core/lib/spree/reporting.rb b/spree/core/lib/spree/reporting.rb
new file mode 100644
index 0000000000..5118be591e
--- /dev/null
+++ b/spree/core/lib/spree/reporting.rb
@@ -0,0 +1,32 @@
+require 'spree/reporting/registry'
+require 'spree/reporting/default_vocabulary'
+require 'spree/reporting/query'
+require 'spree/reporting/result'
+require 'spree/reporting/adapters/base'
+require 'spree/reporting/adapters/live'
+
+module Spree
+ # Semantic reporting layer (see docs/plans/6.0-analytics-semantic-layer.md).
+ #
+ # Developers extend the vocabulary through the registry:
+ #
+ # Spree.reporting.metric :wholesale_margin, sql: '...', base: :line_items, format: :money
+ # Spree.reporting.dimension :warehouse, base: :orders, column: :stock_location_id, lookup: 'Spree::StockLocation'
+ #
+ # Consumers (Admin API, dashboard, saved reports, AI tools) compose queries
+ # against registered names only — see Spree::Reporting::Query.
+ module Reporting
+ class UnknownMember < StandardError
+ attr_reader :kind, :name, :valid
+
+ def initialize(kind, name, valid)
+ @kind = kind
+ @name = name
+ @valid = valid
+ super("Unknown reporting #{kind}: #{name}. Valid #{kind.to_s.pluralize}: #{valid.join(', ')}")
+ end
+ end
+
+ class InvalidQuery < StandardError; end
+ end
+end
diff --git a/spree/core/lib/spree/reporting/adapters/base.rb b/spree/core/lib/spree/reporting/adapters/base.rb
new file mode 100644
index 0000000000..d7f586a2bd
--- /dev/null
+++ b/spree/core/lib/spree/reporting/adapters/base.rb
@@ -0,0 +1,67 @@
+module Spree
+ module Reporting
+ module Adapters
+ # Storage adapter contract. Adapters receive a normalized
+ # Spree::Reporting::Query and return a Spree::Reporting::Result with raw
+ # numeric values — the query never changes shape across adapters, which
+ # is what lets storage move from live OLTP to fact tables (or an
+ # external OLAP store) without touching consumers.
+ #
+ # Post-aggregation metric semantics (value casting, derived ratios, the
+ # nil-baseline growth convention) live here so every adapter reports
+ # identical numbers — the drift between hand-rolled growth
+ # implementations is what this layer replaces.
+ class Base
+ def execute(query)
+ raise NotImplementedError, "#{self.class.name} must implement #execute"
+ end
+
+ protected
+
+ attr_reader :query
+
+ def cast_value(metric, raw)
+ case metric.format
+ when :money, :decimal then raw.to_f.round(2)
+ else raw.to_i
+ end
+ end
+
+ def zero_for(metric)
+ metric.format == :integer ? 0 : 0.0
+ end
+
+ # Computes requested ratio metrics from their aggregated components.
+ 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)
+ end
+ end
+
+ def metric_payload(value, previous)
+ payload = { value: value }
+ if query.compare?
+ payload[:previous] = previous
+ payload[:growth] = growth_rate(value, previous)
+ end
+ payload
+ end
+
+ # Percentage change vs the previous period. nil when there is no
+ # previous-period baseline (previous == 0 with current activity) so
+ # clients can render "new" instead of a misleading 0%.
+ def growth_rate(current, previous)
+ return nil if previous.nil?
+ if previous.zero?
+ return 0.0 if current.zero?
+
+ return nil
+ end
+
+ (((current - previous) / previous.to_f) * 100).round(1)
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/reporting/adapters/live.rb b/spree/core/lib/spree/reporting/adapters/live.rb
new file mode 100644
index 0000000000..0eefd246e7
--- /dev/null
+++ b/spree/core/lib/spree/reporting/adapters/live.rb
@@ -0,0 +1,335 @@
+module Spree
+ module Reporting
+ module Adapters
+ # Compiles reporting queries straight against the transactional schema
+ # through store-scoped associations. Default adapter — zero extra infra.
+ #
+ # Metrics aggregate on their own base relation (:orders or :line_items);
+ # one grouped SQL query runs per base per period and the row sets merge
+ # on dimension keys. Time buckets resolve in the store's timezone and
+ # zero-fill across the requested range. Ranked value-dimension queries
+ # push ORDER BY/LIMIT into SQL, and their comparison period only
+ # aggregates the surviving keys.
+ class Live < Base
+ def execute(query)
+ @query = query
+ @store = query.store
+
+ current = period_data(query.time_range, push_sort: sql_sortable?)
+ previous = query.compare? ? period_data(query.previous_time_range, key_filter: compare_key_filter(current)) : nil
+
+ Result.new(
+ meta: {
+ currency: query.currency,
+ time_range: query.time_range,
+ previous_time_range: query.compare? ? query.previous_time_range : nil,
+ metrics: query.metrics.map(&:name),
+ dimensions: query.dimensions.map { |d| { name: d[:dimension].name, grain: d[:grain] }.compact }
+ },
+ totals: build_totals(current, previous),
+ rows: build_rows(current, previous)
+ )
+ end
+
+ private
+
+ attr_reader :store
+
+ # ---- period execution ----
+
+ def period_data(range, push_sort: false, key_filter: nil)
+ {
+ range: range,
+ totals: aggregate(range, grouped: false),
+ groups: query.dimensions.any? ? aggregate(range, grouped: true, push_sort: push_sort, key_filter: key_filter) : {}
+ }
+ end
+
+ # Runs one SQL query per metric base; returns { key_tuple => { metric => value } }.
+ # Ungrouped aggregates use the single [] key.
+ def aggregate(range, grouped:, push_sort: false, key_filter: nil)
+ rows = Hash.new { |h, k| h[k] = {} }
+
+ query.aggregated_metrics.group_by(&:base).each do |base, metrics|
+ scope = base_scope(base, range)
+ selects = metrics.map { |m| "#{resolve_sql(m.sql)} AS #{metric_alias(m)}" }
+
+ if grouped
+ dimension_selects = query.dimensions.map do |d|
+ "#{dimension_expression(d, base)} AS #{dimension_alias(d)}"
+ end
+ scope = scope.group(query.dimensions.map { |d| Arel.sql(dimension_expression(d, base)) })
+ scope = apply_key_filter(scope, base, key_filter) if key_filter
+ scope = apply_sql_sort(scope, metrics) if push_sort
+ selects = dimension_selects + selects
+ end
+
+ connection.select_all(scope.select(selects.map { |s| Arel.sql(s) }).to_sql).each do |row|
+ key = grouped ? query.dimensions.map { |d| dimension_key(d, row[dimension_alias(d)]) } : []
+ metrics.each { |m| rows[key][m.name] = cast_value(m, row[metric_alias(m)]) }
+ end
+ end
+
+ rows.each_value { |metrics| apply_derived(metrics) }
+ rows
+ end
+
+ # The completed_at range predicate implies completeness, so neither
+ # base needs the `complete` scope on top (merging it would replace the
+ # range condition — Rails merge overwrites same-column wheres).
+ def base_scope(base, range)
+ scope = case base
+ when :orders
+ store.orders.where(currency: query.currency, completed_at: range)
+ when :line_items
+ store.line_items
+ .where(Spree::Order.table_name => { currency: query.currency, completed_at: range })
+ else
+ raise InvalidQuery, "unknown metric base #{base}"
+ end
+
+ # Association default orderings break grouped selects on PostgreSQL.
+ scope = scope.reorder(nil)
+ scope = apply_dimension_joins(scope, base)
+ apply_filters(scope, base)
+ end
+
+ # Dimension joins are declared from their own base; they only apply
+ # when the executing scope is that base (an :orders-based metric never
+ # joins line-item tables — validate_bases! guarantees compatibility).
+ def apply_dimension_joins(scope, base)
+ query.dimensions.each do |d|
+ joins = d[:dimension].joins
+ scope = scope.joins(joins) if joins.present? && d[:dimension].base == base
+ end
+ scope
+ end
+
+ def apply_filters(scope, base)
+ query.filters.each do |filter|
+ column = qualified_column(filter[:dimension], base)
+ scope = scope.joins(filter[:dimension].joins) if filter[:dimension].joins.present? && base == :line_items
+ scope = scope.where("#{column} IN (?)", filter[:values])
+ end
+ scope
+ end
+
+ # ---- sorted/limited rankings ----
+
+ # ORDER BY + LIMIT can move into SQL when one base group carries every
+ # aggregated metric (so the sort metric and the limit apply to the
+ # same query) and the grouping is by value, not time buckets.
+ def sql_sortable?
+ query.sort && query.limit && query.time_dimension.nil? && query.dimensions.any? &&
+ !sort_metric.derived? && query.aggregated_metrics.map(&:base).uniq.one?
+ end
+
+ def sort_metric
+ query.registry.metric!(query.sort[:metric])
+ end
+
+ def apply_sql_sort(scope, metrics)
+ return scope unless metrics.any? { |m| m.name == sort_metric.name }
+
+ scope.order(Arel.sql("#{resolve_sql(sort_metric.sql)} #{query.sort[:direction] == :desc ? 'DESC' : 'ASC'}"))
+ .limit(query.limit)
+ end
+
+ # The comparison period of a ranked value-dimension query only needs
+ # the keys that made the current ranking — not every group in the
+ # store's history. Only kicks in when SQL limited the current period,
+ # so the IN clause is never larger than the limit.
+ def compare_key_filter(current)
+ return unless sql_sortable? && query.dimensions.size == 1
+
+ keys = current[:groups].keys.flatten
+ keys if keys.any?
+ end
+
+ def apply_key_filter(scope, base, keys)
+ dim = query.dimensions.first
+ scope.where("#{dimension_expression(dim, base)} IN (?)", keys)
+ end
+
+ # ---- SQL expressions ----
+
+ def metric_alias(metric)
+ "m_#{metric.name}"
+ end
+
+ # Registered fragments defer table names as %{placeholders} because
+ # model classes cannot load while initializers register the vocabulary.
+ def resolve_sql(fragment)
+ format(fragment,
+ orders: Spree::Order.table_name,
+ line_items: Spree::LineItem.table_name,
+ variants: Spree::Variant.table_name,
+ products: Spree::Product.table_name,
+ product_categories: Spree::ProductCategory.table_name)
+ end
+
+ def dimension_alias(dim)
+ "d_#{dim[:dimension].name}"
+ end
+
+ def dimension_expression(dim, base)
+ dimension = dim[:dimension]
+ return time_bucket_sql(qualified_column(dimension, base), dim[:grain]) if dimension.time?
+
+ qualified_column(dimension, base)
+ end
+
+ def qualified_column(dimension, _base)
+ return resolve_sql(dimension.column) if dimension.column.is_a?(String)
+
+ table = dimension.base == :orders ? Spree::Order.table_name : Spree::LineItem.table_name
+ "#{table}.#{dimension.column}"
+ end
+
+ # Time buckets come back as Date on PostgreSQL and String elsewhere —
+ # normalize to ISO strings so keys merge and zero-fill consistently.
+ def dimension_key(dim, raw)
+ dim[:dimension].time? ? raw.to_s : raw
+ end
+
+ # Store-timezone day/month buckets, per database. PostgreSQL converts
+ # properly (DST-aware); SQLite/MySQL shift by the timezone's current
+ # UTC offset — a documented approximation near DST boundaries.
+ def time_bucket_sql(column, grain)
+ case connection.adapter_name
+ when /postgres/i
+ tz = store_time_zone.tzinfo.identifier
+ case grain
+ when :day then "(#{column} AT TIME ZONE 'UTC' AT TIME ZONE '#{tz}')::date"
+ when :month then "date_trunc('month', #{column} AT TIME ZONE 'UTC' AT TIME ZONE '#{tz}')::date"
+ end
+ when /mysql/i
+ offset = format_offset(utc_offset)
+ case grain
+ when :day then "DATE(CONVERT_TZ(#{column}, '+00:00', '#{offset}'))"
+ when :month then "DATE_FORMAT(CONVERT_TZ(#{column}, '+00:00', '#{offset}'), '%Y-%m-01')"
+ end
+ else # SQLite
+ case grain
+ when :day then "DATE(#{column}, '#{utc_offset} seconds')"
+ when :month then "strftime('%Y-%m-01', #{column}, '#{utc_offset} seconds')"
+ end
+ end
+ end
+
+ def store_time_zone
+ @store_time_zone ||= ActiveSupport::TimeZone[store.preferred_timezone.presence || 'UTC'] || ActiveSupport::TimeZone['UTC']
+ end
+
+ def utc_offset
+ @utc_offset ||= store_time_zone.now.utc_offset
+ end
+
+ def format_offset(seconds)
+ sign = seconds.negative? ? '-' : '+'
+ format("#{sign}%02d:%02d", seconds.abs / 3600, (seconds.abs % 3600) / 60)
+ end
+
+ # ---- result assembly ----
+
+ def build_totals(current, previous)
+ query.metrics.to_h do |metric|
+ value = current[:totals].fetch([], {})[metric.name] || zero_for(metric)
+ prev = previous && (previous[:totals].fetch([], {})[metric.name] || zero_for(metric))
+ [metric.name, metric_payload(value, prev)]
+ end
+ end
+
+ def build_rows(current, previous)
+ return [] if query.dimensions.empty?
+
+ keys = row_keys(current)
+ prev_key_map = previous ? previous_key_map(keys) : {}
+
+ rows = keys.map do |key|
+ metrics = query.metrics.index_by(&:name).transform_values do |metric|
+ value = current[:groups].fetch(key, {})[metric.name] || zero_for(metric)
+ prev = previous && (previous[:groups].fetch(prev_key_map.fetch(key, key), {})[metric.name] || zero_for(metric))
+ metric_payload(value, prev)
+ end
+
+ dimensions = query.dimensions.each_with_index.to_h do |d, index|
+ [d[:dimension].name, key[index]]
+ end
+
+ { dimensions: dimensions, metrics: metrics }
+ end
+
+ sort_rows(rows)
+ end
+
+ # Grouped keys observed in the data, plus zero-filled time buckets
+ # covering the whole range (time-dimension queries chart every bucket).
+ def row_keys(current)
+ keys = current[:groups].keys
+ time_dim = query.time_dimension
+ return keys unless time_dim && query.dimensions.size == 1
+
+ expected_buckets(query.time_range, time_dim[:grain]).map { |bucket| [bucket] }
+ end
+
+ def expected_buckets(range, grain)
+ from = range.first.in_time_zone(store_time_zone).to_date
+ to = range.last.in_time_zone(store_time_zone).to_date
+
+ case grain
+ when :day then (from..to).map(&:to_s)
+ when :month
+ months = []
+ cursor = from.beginning_of_month
+ while cursor <= to
+ months << cursor.to_s
+ cursor = cursor.next_month
+ end
+ months
+ end
+ end
+
+ # Aligns each current bucket with its previous-period counterpart
+ # (same offset from the range start); value-dimension keys align 1:1.
+ def previous_key_map(keys)
+ time_dim = query.time_dimension
+ return {} unless time_dim && query.dimensions.size == 1
+
+ span = offset_span(time_dim[:grain])
+ keys.to_h do |key|
+ date = Date.parse(key.first.to_s)
+ prev = time_dim[:grain] == :day ? date - span : date << span
+ [key, [prev.to_s]]
+ end
+ end
+
+ def offset_span(grain)
+ from = query.time_range.first.in_time_zone(store_time_zone).to_date
+ to = query.time_range.last.in_time_zone(store_time_zone).to_date
+
+ case grain
+ when :day then (to - from).to_i + 1
+ when :month then ((to.year - from.year) * 12) + (to.month - from.month) + 1
+ end
+ end
+
+ # SQL already ordered/limited the pushdown case; this re-sort is a
+ # no-op there and covers the multi-base fallback.
+ def sort_rows(rows)
+ if query.sort
+ metric = query.sort[:metric]
+ rows = rows.sort_by { |row| row[:metrics][metric][:value] }
+ rows.reverse! if query.sort[:direction] == :desc
+ end
+ rows = rows.first(query.limit) if query.limit
+ rows
+ end
+
+ def connection
+ Spree::Order.connection
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/reporting/default_vocabulary.rb b/spree/core/lib/spree/reporting/default_vocabulary.rb
new file mode 100644
index 0000000000..a1566b7625
--- /dev/null
+++ b/spree/core/lib/spree/reporting/default_vocabulary.rb
@@ -0,0 +1,79 @@
+module Spree
+ module Reporting
+ # Core's starter metric/dimension vocabulary. Installed by the engine
+ # initializer before app initializers run, so applications and extensions
+ # can register their own members (or `replace:` these) in
+ # config/initializers.
+ #
+ # Model classes appear only inside lambdas and %{table} placeholders —
+ # nothing here may autoload during initialization.
+ module DefaultVocabulary
+ 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
+ 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
+
+ dimension :completed_at, base: :orders, column: :completed_at, type: :time, grains: %i[day month]
+ dimension :payment_status, base: :orders, column: :payment_status
+ dimension :fulfillment_status, base: :orders, column: :fulfillment_status
+
+ dimension :channel, base: :orders, column: :channel_id, lookup: :channel,
+ resolve: ->(store, value) { store.channels.find_by_prefix_id!(value).id },
+ hydrate: lambda { |store, ids, _params|
+ store.channels.where(id: ids).to_h do |channel|
+ [channel.id, { id: channel.prefixed_id, label: channel.name, meta: { code: channel.code } }]
+ end
+ }
+
+ # Keys are order emails, so guests rank too; the id/profile link is
+ # only present when a registered customer matches.
+ dimension :customer, base: :orders, column: :email, lookup: :customer,
+ subject: -> { Spree.customer_class }, key_scope: 'read_customers',
+ hydrate: lambda { |store, emails, _params|
+ users = store.customers.distinct.where(email: emails).index_by(&:email)
+ emails.to_h do |email|
+ user = users[email]
+ [email, { id: user&.prefixed_id, label: user&.full_name.presence || email, meta: { email: email } }]
+ end
+ }
+
+ dimension :category, base: :line_items, column: '%{product_categories}.category_id',
+ joins: [{ variant: { product: :product_categories } }], lookup: :category,
+ subject: -> { Spree::Category }, key_scope: 'read_categories',
+ resolve: ->(store, value) { store.categories.find_by_prefix_id!(value).id },
+ hydrate: lambda { |store, ids, _params|
+ store.categories.where(id: ids).to_h do |category|
+ [category.id, { id: category.prefixed_id, label: category.name, meta: {} }]
+ end
+ }
+
+ # Meta rides on the admin product serializer so thumbnails match the
+ # rest of the Admin API; the lambda only runs inside API requests.
+ dimension :product, base: :line_items, column: '%{variants}.product_id', joins: [:variant],
+ lookup: :product,
+ subject: -> { Spree::Product }, key_scope: 'read_products',
+ resolve: ->(store, value) { store.products.with_deleted.find_by_prefix_id!(value).id },
+ hydrate: lambda { |store, ids, params|
+ serializer = Spree.api.admin_product_serializer
+ store.products.with_deleted.includes(:primary_media).where(id: ids).to_h do |product|
+ serialized = serializer.new(product, params: params).to_h
+ [product.id, {
+ id: serialized['id'],
+ label: serialized['name'],
+ meta: {
+ slug: serialized['slug'],
+ thumbnail_url: serialized['thumbnail_url'],
+ price: serialized.dig('price', 'display_amount')
+ }
+ }]
+ end
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/reporting/query.rb b/spree/core/lib/spree/reporting/query.rb
new file mode 100644
index 0000000000..b0b78e65fd
--- /dev/null
+++ b/spree/core/lib/spree/reporting/query.rb
@@ -0,0 +1,205 @@
+module Spree
+ module Reporting
+ # Validates a contract query against the registry, normalizes it into an
+ # execution plan (resolved members, time ranges, forced store/currency
+ # scopes, resolved filter values), and runs it through a storage adapter.
+ #
+ # Raises UnknownMember / InvalidQuery for anything outside the registry —
+ # unknown members are rejected, never silently dropped.
+ class Query
+ MAX_LIMIT = 1000
+ DEFAULT_VALUE_LIMIT = 50
+ MAX_DIMENSIONS = 2
+ FILTER_OPS = %w[eq in].freeze
+ COMPARE_MODES = %w[previous_period].freeze
+ RELATIVE_RANGE = /\A-(\d+)d\z/
+
+ attr_reader :store, :registry, :currency, :metrics, :dimensions, :filters,
+ :time_range, :compare, :sort, :limit
+
+ def initialize(store:, params:, registry: Spree.reporting)
+ @store = store
+ @registry = registry
+ params = params.deep_symbolize_keys
+
+ @currency = params[:currency].presence || store.default_currency
+ @metrics = normalize_metrics(params[:metrics])
+ @dimensions = normalize_dimensions(params[:dimensions])
+ @filters = normalize_filters(params[:filters])
+ @time_range = normalize_time_range(params[:time_range])
+ @compare = normalize_compare(params[:compare])
+ @sort = normalize_sort(params[:sort])
+ @limit = normalize_limit(params[:limit])
+ validate_bases!
+ end
+
+ def execute(adapter: Spree::Dependencies.reporting_adapter.constantize.new)
+ resolve_filter_values!
+ adapter.execute(self)
+ end
+
+ # Filter values resolve lazily (prefixed ids → store-scoped record ids)
+ # so authorization can run between construction and execution — a
+ # forbidden member must 403 before an unknown id can 404.
+ def resolve_filter_values!
+ return if @filter_values_resolved
+
+ filters.each do |filter|
+ filter[:values] = filter[:values].map { |value| resolve_filter_value(filter[:dimension], value) }
+ end
+ @filter_values_resolved = true
+ end
+
+ def time_dimension
+ dimensions.find { |d| d[:dimension].time? }
+ end
+
+ # Authorization subjects for this query: order data (the floor for all
+ # reporting) plus every referenced member's declared subject. Every
+ # 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
+ end
+
+ # API-key scopes required beyond `read_reports` (which gates the
+ # 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
+ end
+
+ def referenced_dimensions
+ (dimensions.map { |d| d[:dimension] } + filters.map { |f| f[:dimension] }).uniq
+ end
+
+ # The immediately preceding period of equal length.
+ def previous_time_range
+ duration = time_range.last - time_range.first
+ (time_range.first - duration)..(time_range.last - duration)
+ end
+
+ def compare?
+ compare.present?
+ end
+
+ # All metrics the adapter must aggregate: requested non-derived metrics
+ # plus the hidden components of requested ratios.
+ def aggregated_metrics
+ base = metrics.reject(&:derived?)
+ components = metrics.select(&:derived?).flat_map { |m| m.ratio.map { |name| registry.metric!(name) } }
+ (base + components).uniq(&:name)
+ end
+
+ private
+
+ def normalize_metrics(names)
+ raise InvalidQuery, 'metrics must be a non-empty array' if names.blank?
+
+ Array(names).map { |name| registry.metric!(name) }
+ end
+
+ def normalize_dimensions(list)
+ dims = Array(list).map do |entry|
+ name, grain = entry.is_a?(Hash) ? [entry[:name], entry[:grain]] : [entry, nil]
+ dimension = registry.dimension!(name)
+
+ if dimension.time?
+ grain = (grain || dimension.grains.first).to_sym
+ unless dimension.grains.include?(grain)
+ raise InvalidQuery, "invalid grain #{grain} for #{dimension.name}. Valid grains: #{dimension.grains.join(', ')}"
+ end
+ elsif grain.present?
+ raise InvalidQuery, "dimension #{dimension.name} does not support grains"
+ end
+
+ { dimension: dimension, grain: grain }
+ end
+
+ raise InvalidQuery, "at most #{MAX_DIMENSIONS} dimensions per query" if dims.size > MAX_DIMENSIONS
+ raise InvalidQuery, 'at most one time dimension per query' if dims.count { |d| d[:dimension].time? } > 1
+
+ dims
+ end
+
+ def normalize_filters(list)
+ Array(list).map do |filter|
+ dimension = registry.dimension!(filter[:dimension])
+ op = filter[:op].to_s
+ raise InvalidQuery, "invalid filter op #{op}. Valid ops: #{FILTER_OPS.join(', ')}" unless FILTER_OPS.include?(op)
+ raise InvalidQuery, "filter on #{dimension.name} requires a value" if filter[:value].blank?
+
+ { dimension: dimension, op: op.to_sym, values: Array(filter[:value]) }
+ end
+ end
+
+ def resolve_filter_value(dimension, value)
+ dimension.resolve ? dimension.resolve.call(store, value) : value
+ end
+
+ def normalize_time_range(range)
+ range ||= {}
+ from = parse_time(range[:since], edge: :begin) || 30.days.ago.beginning_of_day
+ to = parse_time(range[:until], edge: :end) || Time.current.end_of_day
+ raise InvalidQuery, 'time_range.since must precede time_range.until' if from > to
+
+ from..to
+ end
+
+ def parse_time(value, edge:)
+ return if value.blank?
+
+ if (match = RELATIVE_RANGE.match(value.to_s))
+ return match[1].to_i.days.ago.beginning_of_day
+ end
+
+ time = Time.zone.parse(value.to_s) || raise(InvalidQuery, "invalid time: #{value}")
+ # Date-only inputs cover the whole day on either edge.
+ if value.to_s !~ /\d:\d/
+ edge == :begin ? time.beginning_of_day : time.end_of_day
+ else
+ time
+ end
+ rescue ArgumentError
+ raise InvalidQuery, "invalid time: #{value}"
+ end
+
+ def normalize_compare(value)
+ return if value.blank?
+ raise InvalidQuery, "invalid compare mode #{value}. Valid modes: #{COMPARE_MODES.join(', ')}" unless COMPARE_MODES.include?(value.to_s)
+
+ value.to_s
+ end
+
+ def normalize_sort(value)
+ return if value.blank?
+
+ descending = value.to_s.start_with?('-')
+ name = value.to_s.delete_prefix('-')
+ raise InvalidQuery, "sort metric #{name} must be requested in metrics" unless metrics.any? { |m| m.name.to_s == name }
+
+ { metric: name.to_sym, direction: descending ? :desc : :asc }
+ end
+
+ def normalize_limit(value)
+ return value.to_i.clamp(1, MAX_LIMIT) if value.present?
+
+ DEFAULT_VALUE_LIMIT if time_dimension.nil? && dimensions.any?
+ end
+
+ # :orders-based metrics cannot be grouped or filtered by :line_items
+ # dimensions (order totals per product/category would double count).
+ def validate_bases!
+ line_item_dims = (dimensions.map { |d| d[:dimension] } + filters.map { |f| f[:dimension] })
+ .select { |d| d.base == :line_items }.uniq
+ return if line_item_dims.empty?
+
+ offenders = aggregated_metrics.select { |m| m.base == :orders }
+ return if offenders.empty?
+
+ raise InvalidQuery,
+ "metrics #{offenders.map(&:name).join(', ')} cannot be grouped by #{line_item_dims.map(&:name).join(', ')}"
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/reporting/registry.rb b/spree/core/lib/spree/reporting/registry.rb
new file mode 100644
index 0000000000..5b9eb2f818
--- /dev/null
+++ b/spree/core/lib/spree/reporting/registry.rb
@@ -0,0 +1,105 @@
+module Spree
+ module Reporting
+ # A metric aggregates rows into one number.
+ #
+ # @!attribute sql
+ # Portable aggregate SQL fragment (no DB-specific functions).
+ # @!attribute base
+ # Root relation the aggregate runs against (:orders or :line_items).
+ # @!attribute format
+ # :money | :integer | :decimal — :money metrics force a single-currency scope.
+ # @!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
+ def derived? = ratio.present?
+ def money? = format == :money
+ end
+
+ # A dimension groups rows. The definition owns every behavior keyed off
+ # it, so an extension-registered dimension works end-to-end (filtering,
+ # hydration, authorization) without touching core.
+ #
+ # @!attribute base
+ # The finest base able to express this grouping (:orders groupings are
+ # also reachable from :line_items via the order join; not vice versa).
+ # @!attribute column
+ # Group-by column (symbol on the base table, or a table-qualified string).
+ # @!attribute joins
+ # Extra association joins the grouping needs (from the base relation).
+ # @!attribute type
+ # :value | :time — :time dimensions take a grain and zero-fill buckets.
+ # @!attribute lookup
+ # Schema tag naming what the dimension's keys identify (e.g. :product) —
+ # set alongside +hydrate+ so clients know display payloads are coming.
+ # @!attribute resolve
+ # ->(store, value) resolving filter values (prefixed ids) to raw keys,
+ # always through store-scoped collections. Omitted = values pass through.
+ # @!attribute hydrate
+ # ->(store, keys, params) returning { raw_key => { id:, label:, meta: } }
+ # display payloads for the API layer. Omitted = raw keys on the wire.
+ # @!attribute subject
+ # -> { SomeClass } authorization subject. JWT admin sessions must be
+ # able to `:read` the class to reference the member; order data itself
+ # is covered by the base Spree::Order check. Lazy so registration never
+ # autoloads models.
+ # @!attribute key_scope
+ # API-key scope (e.g. 'read_products') required alongside `read_reports`
+ # for secret keys to reference the member. Mandatory whenever `subject`
+ # is declared, so key access is decided at registration, never skipped.
+ Dimension = Struct.new(:name, :base, :column, :joins, :type, :grains, :lookup,
+ :resolve, :hydrate, :subject, :key_scope, keyword_init: true) do
+ def time? = type == :time
+ end
+
+ # Allowlist of queryable metrics + dimensions. One global instance lives at
+ # `Spree.reporting`; core seeds the starter vocabulary in the engine
+ # initializer and applications/extensions append theirs in initializer files.
+ class Registry
+ attr_reader :metrics, :dimensions
+
+ def initialize
+ @metrics = {}
+ @dimensions = {}
+ end
+
+ 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
+
+ opts[:format] ||= :integer
+ @metrics[name] = Metric.new(name: name, **opts)
+ end
+
+ def dimension(name, replace: false, **opts)
+ name = name.to_sym
+ raise ArgumentError, "dimension #{name} already registered (pass replace: true to override)" if @dimensions.key?(name) && !replace
+ if opts[:subject] && opts[:key_scope].blank?
+ raise ArgumentError, "dimension #{name} declares a subject and must also declare its key_scope"
+ end
+
+ opts[:type] ||= :value
+ @dimensions[name] = Dimension.new(name: name, **opts)
+ end
+
+ def metric!(name)
+ @metrics[name.to_sym] || raise(UnknownMember.new(:metric, name, @metrics.keys))
+ end
+
+ def dimension!(name)
+ @dimensions[name.to_sym] || raise(UnknownMember.new(:dimension, name, @dimensions.keys))
+ end
+
+ # Serializable introspection payload — drives `GET /reporting/schema`,
+ # admin pickers, and the AI tool schema.
+ def schema
+ {
+ metrics: @metrics.values.map { |m| { name: m.name, format: m.format, derived: m.derived? } },
+ dimensions: @dimensions.values.map do |d|
+ { name: d.name, type: d.type, grains: d.grains, lookup: d.lookup }.compact
+ end
+ }
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/reporting/result.rb b/spree/core/lib/spree/reporting/result.rb
new file mode 100644
index 0000000000..26d0fecb4f
--- /dev/null
+++ b/spree/core/lib/spree/reporting/result.rb
@@ -0,0 +1,10 @@
+module Spree
+ module Reporting
+ # Adapter output. All values are numeric (BigDecimal/Integer) — display
+ # formatting is the API layer's job.
+ #
+ # totals: { metric_name => { value:, previous:, growth: } }
+ # rows: [ { dimensions: { dim_name => raw_key }, metrics: { metric_name => { value:, previous:, growth: } } } ]
+ Result = Struct.new(:meta, :totals, :rows, keyword_init: true)
+ end
+end
diff --git a/spree/core/spec/lib/spree/reporting/query_spec.rb b/spree/core/spec/lib/spree/reporting/query_spec.rb
new file mode 100644
index 0000000000..ffebb129b6
--- /dev/null
+++ b/spree/core/spec/lib/spree/reporting/query_spec.rb
@@ -0,0 +1,229 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Reporting::Query do
+ let(:store) { @default_store }
+
+ def run(params)
+ described_class.new(store: store, params: params).execute
+ end
+
+ 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/)
+ end
+
+ it 'rejects unknown dimensions' do
+ expect { run(metrics: %w[orders_count], dimensions: %w[nope]) }.to raise_error(Spree::Reporting::UnknownMember)
+ end
+
+ it 'rejects empty metrics' do
+ expect { run(metrics: []) }.to raise_error(Spree::Reporting::InvalidQuery, /metrics/)
+ end
+
+ it 'rejects invalid grains' do
+ expect { run(metrics: %w[orders_count], 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' }]) }
+ .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]) }
+ .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') }
+ .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 }]) }
+ .to raise_error(ActiveRecord::RecordNotFound)
+ 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] })
+ expect(query.required_subjects).to contain_exactly(Spree::Order, Spree::Product)
+
+ query = described_class.new(store: store, params: { metrics: %w[orders_count] })
+ expect(query.required_subjects).to contain_exactly(Spree::Order)
+ 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],
+ 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] })
+ expect(query.required_key_scopes).to be_empty
+ 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' }])
+
+ 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.rows.length).to eq(31) # default 30 days + today
+ expect(result.rows).to all(satisfy { |row| row[:metrics][:orders_count][:value].zero? })
+ end
+ end
+
+ context 'with completed orders' do
+ # Distinct line item prices keep ranking expectations deterministic.
+ let!(:order1) { create(:completed_order_with_totals, store: store, completed_at: 5.days.ago, line_items_price: 25) }
+ 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])
+
+ 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[: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))
+ end
+
+ it 'reports nil growth without a previous-period baseline' do
+ result = run(metrics: %w[gross_revenue orders_count], compare: 'previous_period')
+
+ expect(result.totals[:gross_revenue][:growth]).to be_nil
+ expect(result.totals[:orders_count][: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],
+ 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][: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' }],
+ time_range: { since: 7.days.ago.to_date.to_s, until: Time.current.to_date.to_s })
+
+ expect(result.rows.length).to eq(8)
+ end
+
+ it 'filters by channel' 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)
+ 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)
+
+ 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)
+ 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)
+
+ 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][:units_sold][:value]).to be > 0
+ expect(row[:metrics][:net_revenue][: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')
+
+ expect(result.rows.length).to eq(1)
+ expect(result.rows.first[:dimensions][:category]).to eq(category.id)
+ expect(result.rows.first[:metrics][:units_sold][:value]).to be > 0
+ 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)
+ end
+ end
+
+ context 'with orders in both periods' do
+ let!(:recent_order) { create(:completed_order_with_totals, store: store, completed_at: 5.days.ago) }
+ 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')
+
+ expect(result.totals[:orders_count][:previous]).to eq(1)
+ expect(result.totals[:gross_revenue][:growth]).to be_a(Numeric)
+ end
+
+ it 'aligns previous-period day buckets by range offset' do
+ result = run(metrics: %w[orders_count], dimensions: [{ name: 'completed_at', grain: 'day' }],
+ compare: 'previous_period')
+
+ aligned = result.rows.find { |row| row[:metrics][:orders_count][:previous].to_i == 1 }
+ expect(aligned).to be_present
+ end
+ end
+
+ context 'scoping' do
+ # Reassigned after creation: the factory pipeline needs a fully configured
+ # store (delivery setup, prices in currency) and only the stored store_id /
+ # currency columns matter for scoping.
+ let!(:foreign_order) do
+ create(:completed_order_with_totals, store: store, completed_at: 3.days.ago).tap do |order|
+ order.update_columns(store_id: create(:store).id)
+ end
+ end
+ let!(:other_currency_order) do
+ create(:completed_order_with_totals, store: store, completed_at: 3.days.ago).tap do |order|
+ order.update_columns(currency: 'EUR')
+ end
+ 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)
+ end
+
+ it 'reports the requested currency' do
+ result = run(metrics: %w[orders_count], currency: 'EUR')
+ expect(result.totals[:orders_count][:value]).to eq(1)
+ expect(result.meta[:currency]).to eq('EUR')
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/lib/spree/reporting/registry_spec.rb b/spree/core/spec/lib/spree/reporting/registry_spec.rb
new file mode 100644
index 0000000000..d05ec76e65
--- /dev/null
+++ b/spree/core/spec/lib/spree/reporting/registry_spec.rb
@@ -0,0 +1,62 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Reporting::Registry do
+ subject(:registry) { described_class.new }
+
+ describe '#metric' do
+ it 'registers and fetches metrics' do
+ registry.metric :margin, sql: 'SUM(x)', base: :orders, format: :money
+ expect(registry.metric!(:margin).sql).to eq('SUM(x)')
+ expect(registry.metric!('margin').money?).to be true
+ end
+
+ it 'raises on duplicate registration unless replace: true' do
+ registry.metric :margin, sql: 'SUM(x)', base: :orders
+ expect { registry.metric :margin, sql: 'SUM(y)', base: :orders }.to raise_error(ArgumentError, /already registered/)
+
+ registry.metric :margin, sql: 'SUM(y)', base: :orders, replace: true
+ expect(registry.metric!(:margin).sql).to eq('SUM(y)')
+ end
+ end
+
+ describe '#dimension' do
+ it 'registers value dimensions by default' do
+ registry.dimension :warehouse, base: :orders, column: :stock_location_id
+ expect(registry.dimension!(:warehouse).time?).to be false
+ end
+
+ it 'requires a key_scope whenever a subject is declared' do
+ expect do
+ registry.dimension :vendor, base: :orders, column: :vendor_id, subject: -> { Spree::Order }
+ end.to raise_error(ArgumentError, /key_scope/)
+ end
+ end
+
+ describe 'unknown members' do
+ it 'raises UnknownMember naming the valid options' do
+ registry.metric :margin, sql: 'SUM(x)', base: :orders
+
+ expect { registry.metric!(:nope) }.to raise_error(Spree::Reporting::UnknownMember, /margin/)
+ expect { registry.dimension!(:nope) }.to raise_error(Spree::Reporting::UnknownMember)
+ end
+ end
+
+ describe '#schema' do
+ it 'serializes registered members for introspection' do
+ registry.metric :margin, sql: 'SUM(x)', base: :orders, format: :money
+ registry.dimension :day, base: :orders, column: :completed_at, type: :time, grains: %i[day]
+
+ expect(registry.schema[:metrics]).to contain_exactly({ name: :margin, format: :money, derived: false })
+ expect(registry.schema[:dimensions]).to contain_exactly({ name: :day, type: :time, grains: %i[day] })
+ end
+ end
+
+ 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.dimension!(:completed_at).grains).to include(:day)
+ expect(Spree.reporting.dimension!(:product).lookup).to eq(:product)
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index 3567861706..21b5aea3a8 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -69,6 +69,16 @@ describe Spree::Order, type: :model do
it { expect(Spree::Order.not_canceled).not_to include canceled_order }
end
+ describe '.for_channel' do
+ let!(:channel) { create(:channel) }
+ let!(:channeled_order) { create(:order, user: user, channel: channel) }
+
+ it 'filters by the given channel and returns all orders for nil' do
+ expect(described_class.for_channel(channel)).to contain_exactly(channeled_order)
+ expect(described_class.for_channel(nil)).to include(channeled_order, completed_order)
+ end
+ end
+
describe '.search' do
let!(:order_1) { create(:order, number: 'R100', customer: create(:user, email: '[email protected]'), bill_address: create(:address, first_name: 'Don', last_name: 'Roe')) }
let!(:order_2) { create(:order, number: 'R101', customer: create(:user, email: '[email protected]'), bill_address: create(:address, first_name: 'Jane', last_name: 'Gone')) }