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.

Address review findings on the reporting layer

Damian Legawiec3696f4a40488
diff --git a/packages/dashboard/src/components/spree/reporting/growth-badge.tsx b/packages/dashboard/src/components/spree/reporting/growth-badge.tsx
index cc4151fd2c..04ec7756cb 100644
--- a/packages/dashboard/src/components/spree/reporting/growth-badge.tsx
+++ b/packages/dashboard/src/components/spree/reporting/growth-badge.tsx
@@ -8,7 +8,7 @@ import { useTranslation } from 'react-i18next'
* baseline (`growth === null`).
*/
export function GrowthBadge({ growth }: { growth: number | null | undefined }) {
- const { t } = useTranslation()
+ const { t, i18n } = useTranslation()
if (growth === null || growth === undefined) {
return (
@@ -18,7 +18,7 @@ export function GrowthBadge({ growth }: { growth: number | null | undefined }) {
)
}
- const formatted = `${growth > 0 ? '+' : ''}${growth.toLocaleString()}%`
+ const formatted = `${growth > 0 ? '+' : ''}${growth.toLocaleString(i18n.language)}%`
if (growth === 0) {
return (
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
index 9a6dffbeb7..8f8e9eb1b4 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
@@ -118,11 +118,13 @@ function DashboardPage() {
? resolveMetrics(CHART_METRICS, schema)
: CHART_METRICS.map((name) => ({ name, label: name, format: 'decimal', derived: false }))
+ // No `placeholderData`: it belongs to the channel that was selected before,
+ // and showing another channel's counts under this one's name is worse than
+ // showing the skeleton for a moment.
const { data: operations } = useQuery({
queryKey: useResourceKey('dashboard', 'operations', channelId),
queryFn: () => adminClient.dashboard.operations({ channel_id: channelParam }),
staleTime: 5 * 60 * 1000,
- placeholderData: (previousData) => previousData,
})
// A role without `read_reports` (or order data) gets a 403 here — say so
@@ -191,6 +193,7 @@ function DashboardPage() {
<div className="grid gap-6 lg:grid-cols-5">
<OperationsCard
data={operations}
+ channelId={channelParam}
className={rankingTabs.length > 0 ? 'lg:col-span-2' : 'lg:col-span-5'}
/>
{rankingTabs.length > 0 && <RankingsCard scope={scope} tabs={rankingTabs} />}
@@ -253,9 +256,12 @@ const OPERATIONS_ROWS: Array<{
function OperationsCard({
data,
className,
+ channelId,
}: {
data: DashboardOperations | undefined
className: string
+ /** The screen's channel, or undefined for all channels. */
+ channelId: string | undefined
}) {
const { t } = useTranslation()
const { storeId } = Route.useParams()
@@ -270,6 +276,15 @@ function OperationsCard({
<div className="flex flex-col">
{OPERATIONS_ROWS.map(({ key, icon: Icon, link }) => {
const count = data?.[key]
+ // Order counts are channel-scoped, so their lists must be too;
+ // stock counts are store-wide and take no channel filter.
+ const filters =
+ link && channelId && link.to === '/$storeId/orders'
+ ? [
+ ...link.filters,
+ { id: 'home-channel', field: 'channel_id', operator: 'eq', value: channelId },
+ ]
+ : link?.filters
const content = (
<>
<span className="flex size-8 shrink-0 items-center justify-center rounded-md border bg-muted/50">
@@ -298,7 +313,7 @@ function OperationsCard({
key={key}
to={link.to}
params={{ storeId }}
- search={{ filters: link.filters }}
+ search={{ filters }}
className={cn(OPERATIONS_ROW_CLASS, 'hover:bg-muted/25')}
>
{content}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/reports/$reportId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/reports/$reportId.tsx
index 97356a520b..f1b545d498 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/reports/$reportId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/reports/$reportId.tsx
@@ -80,8 +80,12 @@ function ReportDetail({
confirmLabel: t('admin.actions.delete'),
})
if (!ok) return
- await remove.mutateAsync(report.id)
- navigate({ to: '/$storeId/reports', params: { storeId } })
+ // The mutation hook surfaces the error; stay on the report if it failed.
+ const deleted = await remove.mutateAsync(report.id).then(
+ () => true,
+ () => false,
+ )
+ if (deleted) navigate({ to: '/$storeId/reports', params: { storeId } })
}
return (
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 4c0b8637f9..58a0ab7901 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
@@ -9,12 +9,10 @@ module Spree
# GET /api/v3/admin/dashboard/operations
def operations
- threshold = params.fetch(:low_stock_threshold, DashboardOperationsSerializer::DEFAULT_LOW_STOCK_THRESHOLD)
-
serializer = DashboardOperationsSerializer.new(
store: current_store,
channel: requested_channel,
- low_stock_threshold: threshold.to_i.clamp(1, 1000)
+ low_stock_threshold: low_stock_threshold
)
render json: serializer.to_h
@@ -22,6 +20,17 @@ module Spree
private
+ # `?low_stock_threshold[]=1` arrives as an Array, which has no #to_i;
+ # anything that is not a plain integer falls back to the default.
+ def low_stock_threshold
+ value = params[:low_stock_threshold]
+ threshold = value.is_a?(String) || value.is_a?(Integer) ? Integer(value, exception: false) : nil
+
+ (threshold || DashboardOperationsSerializer::DEFAULT_LOW_STOCK_THRESHOLD).clamp(1, 1000)
+ end
+
+ private
+
def action_kind
'read'
end
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 a25f41d9df..3b52a9c695 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
@@ -89,4 +89,10 @@ RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller do
end
end
end
+
+ it 'ignores a non-scalar low_stock_threshold instead of raising' do
+ get :operations, params: { low_stock_threshold: ['1'] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ end
end
diff --git a/spree/core/app/models/spree/exports/report.rb b/spree/core/app/models/spree/exports/report.rb
index b0ba9edf68..1413f6d060 100644
--- a/spree/core/app/models/spree/exports/report.rb
+++ b/spree/core/app/models/spree/exports/report.rb
@@ -66,6 +66,8 @@ module Spree
def query_params
raw = search_params.is_a?(String) ? JSON.parse(search_params) : (search_params || {})
+ raise Spree::Reporting::InvalidQuery, 'search_params must be an object' unless raw.is_a?(Hash)
+
raw['query'] || raw[:query] || {}
end
diff --git a/spree/core/lib/spree/reporting/adapters/live.rb b/spree/core/lib/spree/reporting/adapters/live.rb
index 1ef3a824a9..f84c1de6ae 100644
--- a/spree/core/lib/spree/reporting/adapters/live.rb
+++ b/spree/core/lib/spree/reporting/adapters/live.rb
@@ -138,7 +138,14 @@ module Spree
# identifier (see #qualified_column) and the values bind as parameters,
# so no request data reaches the statement as text.
def in_predicate(column, values)
- Arel::Nodes::SqlLiteral.new(column).in(values)
+ node = Arel::Nodes::SqlLiteral.new(column)
+ present, null = Array(values).partition { |value| !value.nil? }
+ # `IN (NULL)` never matches, so a NULL group would silently drop out
+ # of the comparison period and report a zero previous value.
+ return node.in(present) if null.empty?
+ return node.eq(nil) if present.empty?
+
+ node.in(present).or(node.eq(nil))
end
# Dimension joins are declared from the dimension's own base. Reaching
@@ -375,14 +382,17 @@ module Spree
end
# Both periods span the same number of days, so their bucket counts
- # differ by at most one partial edge; pairing from the end keeps the
- # most recent buckets — the ones a merchant reads first — aligned.
+ # differ by at most one partial edge. Pairing runs from the start —
+ # the nth bucket of this period with the nth of the previous — because
+ # the ranges share a start offset: a range beginning mid-month pairs
+ # its partial first bucket with the previous period's partial first
+ # bucket. A bucket past the end of the previous list has no
+ # counterpart and pairs with nothing rather than wrapping around.
def bucket_pairs(grain)
current = expected_buckets(query.time_range, grain)
previous = expected_buckets(query.previous_time_range, grain)
- offset = previous.size - current.size
- current.each_with_index.to_h { |bucket, position| [bucket, previous[position + offset]] }
+ current.each_with_index.to_h { |bucket, position| [bucket, previous[position]] }
end
# SQL already ordered/limited the pushdown case; this re-sort is a
diff --git a/spree/core/lib/spree/reporting/query.rb b/spree/core/lib/spree/reporting/query.rb
index b8d788f4d2..6b277ce1d9 100644
--- a/spree/core/lib/spree/reporting/query.rb
+++ b/spree/core/lib/spree/reporting/query.rb
@@ -251,9 +251,13 @@ module Spree
end
def normalize_limit(value)
- return value.to_i.clamp(1, MAX_LIMIT) if value.present?
+ return DEFAULT_VALUE_LIMIT if value.blank? && time_dimension.nil? && dimensions.any?
+ return if value.blank?
+
+ limit = Integer(value, exception: false)
+ raise InvalidQuery, "limit must be an integer between 1 and #{MAX_LIMIT}" if limit.nil? || limit < 1
- DEFAULT_VALUE_LIMIT if time_dimension.nil? && dimensions.any?
+ limit.clamp(1, MAX_LIMIT)
end
# :orders-based metrics cannot be grouped or filtered by :line_items
diff --git a/spree/core/spec/lib/spree/reporting/query_spec.rb b/spree/core/spec/lib/spree/reporting/query_spec.rb
index f6c089b5f2..18779dcfe6 100644
--- a/spree/core/spec/lib/spree/reporting/query_spec.rb
+++ b/spree/core/spec/lib/spree/reporting/query_spec.rb
@@ -55,6 +55,13 @@ RSpec.describe Spree::Reporting::Query do
expect { run(metrics: %w[orders_count], time_range: 'last_month') }.to raise_error(Spree::Reporting::InvalidQuery)
end
+ it 'refuses a limit that is not a positive integer' do
+ expect { run(metrics: %w[orders_count], dimensions: %w[channel], limit: 'abc') }
+ .to raise_error(Spree::Reporting::InvalidQuery, /limit/)
+ expect { run(metrics: %w[orders_count], dimensions: %w[channel], limit: 0) }
+ .to raise_error(Spree::Reporting::InvalidQuery, /limit/)
+ end
+
it 'refuses partial times instead of filling in today' do
expect { run(metrics: %w[orders_count], time_range: { since: '09:00' }) }
.to raise_error(Spree::Reporting::InvalidQuery, /ISO 8601/)
@@ -388,6 +395,27 @@ RSpec.describe Spree::Reporting::Query do
end
end
+ context 'when the two periods yield different bucket counts' do
+ # Aug 2 – Aug 31 spans six week buckets (the first starts Jul 27, before
+ # the range); the previous period, Jul 3 – Aug 1, spans five. Pairing
+ # runs from the start, and the trailing bucket with no counterpart must
+ # not wrap around to the newest previous one.
+ let!(:recent_order) { create(:completed_order_with_totals, store: store, completed_at: '2026-08-04 12:00'.in_time_zone) }
+ let!(:previous_order) { create(:completed_order_with_totals, store: store, completed_at: '2026-07-07 12:00'.in_time_zone) }
+
+ it 'pairs from the start and leaves the trailing bucket unpaired' do
+ result = run(metrics: %w[orders_count], dimensions: [{ name: 'completed_at', grain: 'week' }],
+ compare: 'previous_period', time_range: { since: '2026-08-02', until: '2026-08-31' })
+
+ paired = result.rows.find { |row| row[:dimensions][:completed_at] == '2026-08-03' }
+ expect(paired[:metrics][:orders_count][:value]).to eq(1)
+ expect(paired[:metrics][:orders_count][:previous]).to eq(1)
+
+ trailing = result.rows.find { |row| row[:dimensions][:completed_at] == '2026-08-31' }
+ expect(trailing[:metrics][:orders_count][:previous]).to eq(0)
+ end
+ end
+
context 'with a quarter-to-date style range at month grain' do
# Range: the 1st of the month before last → today, spanning three
# calendar months with the current one partial. Each month bucket must
diff --git a/spree/core/spec/models/spree/exports/report_spec.rb b/spree/core/spec/models/spree/exports/report_spec.rb
index 099c6f857f..7cd5d72a46 100644
--- a/spree/core/spec/models/spree/exports/report_spec.rb
+++ b/spree/core/spec/models/spree/exports/report_spec.rb
@@ -24,6 +24,12 @@ RSpec.describe Spree::Exports::Report, type: :model do
expect(rows.last.last.to_i).to eq(1)
end
+ it 'refuses search_params that are not an object' do
+ export = described_class.new(store: store, user: admin, search_params: '[]')
+ expect(export).not_to be_valid
+ expect(export.errors[:search_params]).to be_present
+ end
+
it 'refuses at create a query that does not compile' do
export = described_class.new(store: store, user: admin, search_params: { query: { 'metrics' => %w[nope] } })
expect(export).not_to be_valid