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.

Fix: report builder could not select non-sales metrics (#14663)

Damian Legawiec547deb570cfc
diff --git a/packages/dashboard/e2e/reports.spec.ts b/packages/dashboard/e2e/reports.spec.ts
index be503af122..70dc68a2c4 100644
--- a/packages/dashboard/e2e/reports.spec.ts
+++ b/packages/dashboard/e2e/reports.spec.ts
@@ -85,4 +85,26 @@ test.describe('reports', () => {
})
await expect(page.getByRole('link', { name: `${name} renamed` })).toHaveCount(0)
})
+
+ test('switches the report to another metric group', async ({ page }) => {
+ const creds = await login(page)
+ await page.goto(`${REPORTS_PATH(creds.store_id)}/new`)
+
+ await expect(page.getByRole('heading', { name: /^new report$/i })).toBeVisible({
+ timeout: 15_000,
+ })
+
+ // A new report opens on sales, so a payments metric belongs to another
+ // group — it must still be pickable, and picking it switches the report.
+ const payments = page.getByRole('checkbox', { name: /^payments received$/i })
+ await expect(payments).toBeEnabled()
+ await payments.check()
+
+ await expect(payments).toBeChecked()
+ await expect(page.getByRole('checkbox', { name: /^total sales$/i })).not.toBeChecked()
+ // The breakdown followed the switch onto the payments clock, so the
+ // report still charts a series rather than dropping to bare totals.
+ await expect(page.getByRole('combobox', { name: /group by/i })).toHaveText(/payment date/i)
+ await expect(page.getByText(/pick at least one metric/i)).toHaveCount(0)
+ })
})
diff --git a/packages/dashboard/src/components/spree/reporting/report-builder.tsx b/packages/dashboard/src/components/spree/reporting/report-builder.tsx
index 79a56dcf3e..d705854d9b 100644
--- a/packages/dashboard/src/components/spree/reporting/report-builder.tsx
+++ b/packages/dashboard/src/components/spree/reporting/report-builder.tsx
@@ -41,6 +41,8 @@ import { useAllMarkets } from '../../../hooks/use-markets'
import { productAutocompleteProps } from '../../../hooks/use-products'
import {
maxBuckets as bucketCeiling,
+ draftWithMetric,
+ familyOfMetrics,
findDimension,
hourGrainFitsRange,
isTimeDimension,
@@ -72,9 +74,9 @@ export function ReportBuilder({ draft, onChange, schema }: ReportBuilderProps) {
const update = (patch: Partial<ReportDraft>) => onChange({ ...draft, ...patch })
// Metrics from different families cannot be combined in one query, so the
- // picker groups them and disables the families the current selection has
- // ruled out — the alternative is a flat run of 27 checkboxes where the
- // refusal only arrives after you have picked an impossible pair.
+ // picker groups them by family — the alternative is a flat run of 27
+ // checkboxes where the refusal only arrives after an impossible pair.
+ // Picking across families switches the report rather than being refused.
const metricGroups =
schema.families?.length > 0
? schema.families
@@ -87,10 +89,8 @@ export function ReportBuilder({ draft, onChange, schema }: ReportBuilderProps) {
: [{ name: 'all', label: '', metrics: schema.metrics }]
// Whichever family the current selection belongs to; null while nothing is
- // picked, so every family stays open.
- const activeFamily =
- metricGroups.find((group) => group.metrics.some((m) => draft.metrics.includes(m.name)))?.name ??
- null
+ // picked, so every family reads as equally available.
+ const activeFamily = familyOfMetrics(schema, draft.metrics)?.name ?? null
const groupableDimensions = schema.dimensions.filter((d) =>
draft.metrics.every((metric) => d.compatible_metrics.includes(metric)),
@@ -158,10 +158,7 @@ export function ReportBuilder({ draft, onChange, schema }: ReportBuilderProps) {
]
function toggleMetric(name: string, checked: boolean) {
- const metrics = checked
- ? [...draft.metrics, name]
- : draft.metrics.filter((metric) => metric !== name)
- update({ metrics })
+ onChange(draftWithMetric(draft, schema, name, checked))
}
function setDimension(value: string) {
@@ -223,13 +220,17 @@ export function ReportBuilder({ draft, onChange, schema }: ReportBuilderProps) {
)}
{group.metrics.map((metric) => {
const id = `metric-${metric.name}`
- // Greyed out when the chosen breakdown, an active filter, or a
- // metric from another family cannot be combined with this one.
+ // A metric outside the report's current family stays clickable:
+ // ticking it switches the report to that family, which is what
+ // a merchant means by it.
+ const otherFamily = activeFamily !== null && group.name !== activeFamily
+ // Greyed out only when the breakdown or a filter this report
+ // already carries cannot break this metric down.
const incompatible =
+ !otherFamily &&
[dimension, ...draft.filters.map((f) => findDimension(schema, f.dimension))].some(
(d) => d && !d.compatible_metrics.includes(metric.name),
- ) ||
- (activeFamily !== null && group.name !== activeFamily)
+ )
return (
<Field key={metric.name} orientation="horizontal">
<Checkbox
@@ -240,7 +241,11 @@ export function ReportBuilder({ draft, onChange, schema }: ReportBuilderProps) {
/>
<FieldLabel
htmlFor={id}
- title={metric.description ?? undefined}
+ title={
+ otherFamily
+ ? t('admin.reports.builder.switches_family', { family: group.label })
+ : (metric.description ?? undefined)
+ }
className={cn('font-normal', incompatible && 'text-muted-foreground')}
>
{metric.label}
@@ -250,8 +255,14 @@ export function ReportBuilder({ draft, onChange, schema }: ReportBuilderProps) {
})}
</div>
))}
- {draft.metrics.length === 0 && (
+ {draft.metrics.length === 0 ? (
<p className="text-xs text-destructive">{t('admin.reports.builder.no_metrics')}</p>
+ ) : (
+ metricGroups.length > 1 && (
+ <p className="text-xs text-muted-foreground">
+ {t('admin.reports.builder.one_family_only')}
+ </p>
+ )
)}
</FieldSet>
diff --git a/packages/dashboard/src/components/spree/reporting/report-draft.test.ts b/packages/dashboard/src/components/spree/reporting/report-draft.test.ts
new file mode 100644
index 0000000000..a48e87260d
--- /dev/null
+++ b/packages/dashboard/src/components/spree/reporting/report-draft.test.ts
@@ -0,0 +1,187 @@
+import type { ReportingSchema } from '@spree/admin-sdk'
+import { describe, expect, it } from 'vitest'
+import { draftFromQuery, draftWithMetric, familyOfMetrics } from './report-draft'
+
+// A cut-down stand-in for the real schema: two families, each with its own
+// time dimension, plus one value dimension per family.
+const schema = {
+ meta: { currency: 'USD', timezone: 'UTC', supported_currencies: ['USD'] },
+ families: [
+ {
+ name: 'sales',
+ label: 'Sales',
+ metrics: ['total_sales', 'orders'],
+ dimensions: ['completed_at', 'payment_status'],
+ },
+ {
+ name: 'payments',
+ label: 'Payments',
+ metrics: ['payments_received'],
+ dimensions: ['paid_at', 'payment_method'],
+ },
+ ],
+ metrics: [
+ { name: 'total_sales', family: 'sales', label: 'Total sales', format: 'money', derived: false },
+ { name: 'orders', family: 'sales', label: 'Orders', format: 'integer', derived: false },
+ {
+ name: 'payments_received',
+ family: 'payments',
+ label: 'Payments received',
+ format: 'money',
+ derived: false,
+ },
+ ],
+ dimensions: [
+ {
+ name: 'completed_at',
+ label: 'Order date',
+ type: 'time',
+ grains: ['hour', 'day', 'week'],
+ filter_ops: ['eq', 'in'] as Array<'eq' | 'in'>,
+ compatible_metrics: ['total_sales', 'orders'],
+ },
+ {
+ name: 'payment_status',
+ label: 'Payment status',
+ type: 'value',
+ filter_ops: ['eq', 'in'] as Array<'eq' | 'in'>,
+ compatible_metrics: ['total_sales', 'orders'],
+ },
+ {
+ name: 'paid_at',
+ label: 'Payment date',
+ type: 'time',
+ grains: ['hour', 'day', 'week'],
+ filter_ops: ['eq', 'in'] as Array<'eq' | 'in'>,
+ compatible_metrics: ['payments_received'],
+ },
+ {
+ name: 'payment_method',
+ label: 'Payment method',
+ type: 'value',
+ filter_ops: ['eq', 'in'] as Array<'eq' | 'in'>,
+ compatible_metrics: ['payments_received'],
+ },
+ ],
+ time_range: {
+ presets: [{ name: 'last_4_weeks', label: 'Last 4 weeks' }],
+ relative: [],
+ absolute: '',
+ },
+ limits: { default: 50, max: 500, max_buckets: 2000 },
+} as unknown as ReportingSchema
+
+const salesDraft = () =>
+ draftFromQuery(
+ {
+ metrics: ['total_sales', 'orders'],
+ dimensions: [{ name: 'completed_at', grain: 'day' }],
+ time_range: { preset: 'last_4_weeks' },
+ },
+ schema,
+ )
+
+describe('familyOfMetrics', () => {
+ it('names the family the selection belongs to', () => {
+ expect(familyOfMetrics(schema, ['orders'])?.name).toBe('sales')
+ expect(familyOfMetrics(schema, ['payments_received'])?.name).toBe('payments')
+ })
+
+ it('answers null for an empty selection', () => {
+ expect(familyOfMetrics(schema, [])).toBeNull()
+ })
+})
+
+describe('draftWithMetric', () => {
+ it('adds and removes a metric within one family', () => {
+ const draft = salesDraft()
+
+ const without = draftWithMetric(draft, schema, 'orders', false)
+ expect(without.metrics).toEqual(['total_sales'])
+ expect(without.dimension).toBe('completed_at')
+
+ const back = draftWithMetric(without, schema, 'orders', true)
+ expect(back.metrics).toEqual(['total_sales', 'orders'])
+ })
+
+ it('switches family and moves the breakdown to that family’s time dimension', () => {
+ const next = draftWithMetric(salesDraft(), schema, 'payments_received', true)
+
+ expect(next.metrics).toEqual(['payments_received'])
+ expect(next.dimension).toBe('paid_at')
+ expect(next.grain).toBe('day')
+ })
+
+ it('keeps the grain when switching family', () => {
+ const hourly = { ...salesDraft(), grain: 'hour' as const, timeRange: { preset: 'today' } }
+
+ expect(draftWithMetric(hourly, schema, 'payments_received', true).grain).toBe('hour')
+ })
+
+ it('drops filters the new family cannot express', () => {
+ const filtered = {
+ ...salesDraft(),
+ filters: [{ dimension: 'payment_status', values: ['paid'] }],
+ }
+
+ const next = draftWithMetric(filtered, schema, 'payments_received', true)
+
+ expect(next.filters).toEqual([])
+ })
+
+ it('carries no breakdown across families when the current one is not a time dimension', () => {
+ const ranked = { ...salesDraft(), dimension: 'payment_status', sortMetric: 'orders' }
+
+ const next = draftWithMetric(ranked, schema, 'payments_received', true)
+
+ expect(next.dimension).toBeNull()
+ expect(next.sortMetric).toBeNull()
+ })
+
+ it('clears a breakdown the remaining metrics can no longer be grouped by', () => {
+ const mixed = { ...salesDraft(), metrics: ['payments_received'], dimension: 'paid_at' }
+
+ // Ticking a sales metric switches back, so paid_at cannot survive.
+ const next = draftWithMetric(mixed, schema, 'orders', true)
+
+ expect(next.metrics).toEqual(['orders'])
+ expect(next.dimension).toBe('completed_at')
+ })
+
+ it('clears the breakdown once the last metric is unticked', () => {
+ let draft = draftWithMetric(salesDraft(), schema, 'total_sales', false)
+ draft = draftWithMetric(draft, schema, 'orders', false)
+
+ expect(draft.metrics).toEqual([])
+ // A leftover sales breakdown would rule out every other family's metrics.
+ expect(draft.dimension).toBeNull()
+ })
+
+ it('reaches another family after the defaults are cleared', () => {
+ let draft = draftWithMetric(salesDraft(), schema, 'total_sales', false)
+ draft = draftWithMetric(draft, schema, 'orders', false)
+
+ const next = draftWithMetric(draft, schema, 'payments_received', true)
+
+ expect(next.metrics).toEqual(['payments_received'])
+ expect(next.dimension).toBeNull()
+ })
+
+ it('drops a filter left behind by clearing every metric', () => {
+ const filtered = {
+ ...salesDraft(),
+ filters: [{ dimension: 'payment_status', values: ['paid'] }],
+ }
+
+ let draft = draftWithMetric(filtered, schema, 'total_sales', false)
+ draft = draftWithMetric(draft, schema, 'orders', false)
+
+ expect(draft.filters).toEqual([])
+ })
+
+ it('leaves the draft alone when the schema has not loaded', () => {
+ const next = draftWithMetric(salesDraft(), undefined, 'payments_received', true)
+
+ expect(next.metrics).toEqual(['total_sales', 'orders', 'payments_received'])
+ })
+})
diff --git a/packages/dashboard/src/components/spree/reporting/report-draft.ts b/packages/dashboard/src/components/spree/reporting/report-draft.ts
index ba3bb6096c..1140fa3b1a 100644
--- a/packages/dashboard/src/components/spree/reporting/report-draft.ts
+++ b/packages/dashboard/src/components/spree/reporting/report-draft.ts
@@ -3,6 +3,7 @@ import type {
ReportingQuery,
ReportingSchema,
ReportingSchemaDimension,
+ ReportingSchemaFamily,
} from '@spree/admin-sdk'
export const DEFAULT_PRESET = 'last_4_weeks'
@@ -187,3 +188,108 @@ export function inferViz(query: ReportingQuery, schema?: ReportingSchema): Repor
const time = definition ? isTimeDimension(definition) : !!dimension.grain
return time ? 'chart' : 'ranking'
}
+
+/**
+ * The family a set of metrics belongs to, or null when nothing is selected.
+ * Metrics from two families cannot be queried together, so the first match
+ * is the whole answer.
+ */
+export function familyOfMetrics(
+ schema: ReportingSchema | undefined,
+ metrics: string[],
+): ReportingSchemaFamily | null {
+ return (
+ schema?.families?.find((family) => metrics.some((metric) => family.metrics.includes(metric))) ??
+ null
+ )
+}
+
+/**
+ * The draft after a metric is ticked or unticked, carrying the breakdown and
+ * filters with it.
+ *
+ * Ticking a metric from another family replaces the selection rather than
+ * refusing it: each family measures a different thing over its own time axis
+ * (orders by order date, payments by capture date), so "payments received"
+ * cannot mean "and also keep total sales". The breakdown moves to the new
+ * family's own time dimension so the report still charts something, and
+ * filters the new family cannot express are dropped — leaving them would send
+ * a query the server refuses with nothing on screen to explain it.
+ */
+export function draftWithMetric(
+ draft: ReportDraft,
+ schema: ReportingSchema | undefined,
+ name: string,
+ checked: boolean,
+): ReportDraft {
+ const metrics = checked
+ ? [...draft.metrics, name]
+ : draft.metrics.filter((metric) => metric !== name)
+
+ const previousFamily = familyOfMetrics(schema, draft.metrics)
+ const nextFamily = familyOfMetrics(schema, [name])
+ const switching =
+ checked &&
+ previousFamily != null &&
+ nextFamily != null &&
+ previousFamily.name !== nextFamily.name
+
+ const next: ReportDraft = switching
+ ? { ...draft, metrics: [name], dimension: replacementDimension(draft, schema, nextFamily) }
+ : { ...draft, metrics }
+
+ return withServableSelection(next, schema)
+}
+
+/**
+ * The breakdown to carry into another family: its time dimension when the
+ * current breakdown is one (a daily series stays daily, on the new family's
+ * own clock), otherwise nothing, since no non-time dimension is shared across
+ * families.
+ */
+function replacementDimension(
+ draft: ReportDraft,
+ schema: ReportingSchema | undefined,
+ family: ReportingSchemaFamily,
+): string | null {
+ if (!draft.dimension) return null
+ const current = findDimension(schema, draft.dimension)
+ if (!isTimeDimension(current)) return null
+ const dimensions = (schema?.dimensions ?? []).filter((d) => family.dimensions.includes(d.name))
+ return dimensions.find((d) => isTimeDimension(d))?.name ?? null
+}
+
+/**
+ * The draft with the breakdown, filters and sort metric the current metrics
+ * can actually be queried with. Called after every metric change so an
+ * incompatible leftover is cleared at the moment it becomes impossible,
+ * rather than surviving to be refused by the server.
+ */
+export function withServableSelection(
+ draft: ReportDraft,
+ schema: ReportingSchema | undefined,
+): ReportDraft {
+ // An empty selection commits to no family, so nothing is servable: a
+ // breakdown left over from the metrics just cleared would otherwise keep
+ // ruling out every other family's metrics, which is the dead end a merchant
+ // hits by unticking the defaults before picking what they actually wanted.
+ const servable = (name: string | null | undefined) => {
+ const definition = findDimension(schema, name)
+ if (!definition) return true
+ if (draft.metrics.length === 0) return false
+ return draft.metrics.every((m) => definition.compatible_metrics.includes(m))
+ }
+
+ const dimension = servable(draft.dimension) ? draft.dimension : null
+ const filters = draft.filters.filter((filter) => servable(filter.dimension))
+ const sortMetric =
+ draft.sortMetric && draft.metrics.includes(draft.sortMetric) ? draft.sortMetric : null
+
+ return {
+ ...draft,
+ dimension,
+ grain: servableGrain(draft, findDimension(schema, dimension), maxBuckets(schema)),
+ filters,
+ sortMetric,
+ }
+}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 29343b152e..a206e57c34 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -5926,6 +5926,8 @@
"builder": {
"metrics": "المقاييس",
"no_metrics": "اختر مقياسًا واحدًا على الأقل.",
+ "one_family_only": "يغطي التقرير الواحد مجموعة مقاييس واحدة. اختيار مقياس من مجموعة أخرى ينقل التقرير إلى تلك المجموعة.",
+ "switches_family": "ينقل هذا التقرير إلى {{family}}",
"group_by": "تجميع حسب",
"none": "بدون (الإجماليات فقط)",
"grain": "الفاصل الزمني",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 3d325cb92e..bf48095cef 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -5889,6 +5889,8 @@
"builder": {
"metrics": "Kennzahlen",
"no_metrics": "Wählen Sie mindestens eine Kennzahl.",
+ "one_family_only": "Ein Bericht umfasst eine Metrikgruppe. Die Auswahl einer Metrik aus einer anderen Gruppe wechselt den Bericht zu dieser Gruppe.",
+ "switches_family": "Wechselt diesen Bericht zu {{family}}",
"group_by": "Gruppieren nach",
"none": "Keine (nur Summen)",
"grain": "Intervall",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 82ef67bece..f5f0326607 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -5889,6 +5889,8 @@
"builder": {
"metrics": "Metrics",
"no_metrics": "Pick at least one metric.",
+ "one_family_only": "One report covers one metric group. Picking a metric from another group switches the report to it.",
+ "switches_family": "Switches this report to {{family}}",
"group_by": "Group by",
"none": "None (totals only)",
"grain": "Interval",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 3d5ffbe7f6..8057685069 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -5889,6 +5889,8 @@
"builder": {
"metrics": "Indicateurs",
"no_metrics": "Choisissez au moins un indicateur.",
+ "one_family_only": "Un rapport couvre un seul groupe de mesures. Choisir une mesure d'un autre groupe fait basculer le rapport vers ce groupe.",
+ "switches_family": "Fait basculer ce rapport vers {{family}}",
"group_by": "Regrouper par",
"none": "Aucun (totaux uniquement)",
"grain": "Intervalle",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 749a6454ab..2dbe5569b7 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -5955,6 +5955,8 @@
"builder": {
"metrics": "Metryki",
"no_metrics": "Wybierz co najmniej jedną metrykę.",
+ "one_family_only": "Jeden raport obejmuje jedną grupę wskaźników. Wybór wskaźnika z innej grupy przełącza raport na tę grupę.",
+ "switches_family": "Przełącza ten raport na {{family}}",
"group_by": "Grupuj według",
"none": "Brak (tylko sumy)",
"grain": "Interwał",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 1eb4221431..9317a65b4f 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -5876,6 +5876,8 @@
"builder": {
"metrics": "指标",
"no_metrics": "请至少选择一个指标。",
+ "one_family_only": "一个报表只涵盖一个指标组。选择其他组中的指标会将报表切换到该组。",
+ "switches_family": "将此报表切换到{{family}}",
"group_by": "分组依据",
"none": "无(仅汇总)",
"grain": "时间粒度",