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: five findings from review of the reporting layer

Damian Legawiec173b8ed43b30
diff --git a/packages/dashboard/src/hooks/use-dashboard-counters.ts b/packages/dashboard/src/hooks/use-dashboard-counters.ts
index db71787f91..0011bf4202 100644
--- a/packages/dashboard/src/hooks/use-dashboard-counters.ts
+++ b/packages/dashboard/src/hooks/use-dashboard-counters.ts
@@ -18,10 +18,14 @@ export function useDashboardCounters(channelId?: string) {
return useQuery({
queryKey: useResourceKey('dashboard', 'counters', channelId),
queryFn: () => adminClient.dashboard.counters({ channel_id: channelId }),
- // No `placeholderData`: it would belong to the channel selected before,
- // and showing another channel's counts under this one's name is worse
- // than showing the skeleton for a moment.
- staleTime: 5 * 60 * 1000,
+ // Deliberately no `staleTime`: these count work still waiting on the
+ // merchant, and acting on a record invalidates this key — a stale window
+ // would hold the old number past that invalidation, so a return they just
+ // refunded would keep its badge.
+ //
+ // No `placeholderData` either: it would belong to the channel selected
+ // before, and showing another channel's counts under this one's name is
+ // worse than showing the skeleton for a moment.
})
}
diff --git a/packages/dashboard/src/hooks/use-returns.ts b/packages/dashboard/src/hooks/use-returns.ts
index 8242a0d960..23b629f52a 100644
--- a/packages/dashboard/src/hooks/use-returns.ts
+++ b/packages/dashboard/src/hooks/use-returns.ts
@@ -36,7 +36,7 @@ function useReturnMutation<TParams>(
queryClient.invalidateQueries({ queryKey: buildKey('orders', orderId) })
// Keyed separately from the per-order list, so the sidebar count would
// otherwise stay stale until a page reload.
- queryClient.invalidateQueries({ queryKey: buildKey('returns-pending') })
+ queryClient.invalidateQueries({ queryKey: buildKey('dashboard', 'counters') })
},
onError: (error) => {
// Without this a rejected workflow — a claim with nothing to refund, a
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
index 53c167de05..f868976e10 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
@@ -260,7 +260,10 @@ function counterLink(
// Order counts are channel-scoped, so their lists must be too; stock and
// returns are store-wide and take no channel filter.
if (channelId && link.resource === 'orders') {
- filters.push({ id: 'home-channel', field: 'channel_id', operator: 'eq', value: channelId })
+ // The orders table's column key, not its ransack attribute — the filter
+ // chip looks the column up by key to render "Channel is Web" rather than
+ // the raw id.
+ filters.push({ id: 'home-channel', field: 'channel', operator: 'eq', value: channelId })
}
return { to, filters }
}
diff --git a/spree/core/app/models/concerns/spree/admin_user_methods.rb b/spree/core/app/models/concerns/spree/admin_user_methods.rb
index 403274b0f4..83a3b0f1e6 100644
--- a/spree/core/app/models/concerns/spree/admin_user_methods.rb
+++ b/spree/core/app/models/concerns/spree/admin_user_methods.rb
@@ -44,6 +44,7 @@ module Spree
has_many :created_claims, class_name: 'Spree::Claim', foreign_key: :created_by_id
has_many :created_store_credits, class_name: 'Spree::StoreCredit', foreign_key: :created_by_id
has_many :exports, class_name: 'Spree::Export', foreign_key: :user_id
+ has_many :saved_reports, class_name: 'Spree::SavedReport', foreign_key: :user_id
# Callbacks
after_destroy :nullify_approver_id_in_approved_orders
@@ -96,6 +97,7 @@ module Spree
created_exchanges.update_all(created_by_id: nil, updated_at: Time.current)
created_claims.update_all(created_by_id: nil, updated_at: Time.current)
created_store_credits.update_all(created_by_id: nil, updated_at: Time.current)
+ saved_reports.update_all(user_id: nil, updated_at: Time.current)
# resources to destroy
exports.destroy_all
diff --git a/spree/core/lib/spree/reporting/adapters/live.rb b/spree/core/lib/spree/reporting/adapters/live.rb
index 0dd962485e..391881d66e 100644
--- a/spree/core/lib/spree/reporting/adapters/live.rb
+++ b/spree/core/lib/spree/reporting/adapters/live.rb
@@ -11,6 +11,10 @@ module Spree
# push ORDER BY/LIMIT into SQL, and their comparison period only
# aggregates the surviving keys.
class Live < Base
+ # Roughly a century — long enough for any report a merchant would read,
+ # short enough that the widest one still fits in memory at day grain.
+ MAX_RANGE_DAYS = 36_600
+
def execute(query)
@query = query
@@ -357,9 +361,19 @@ module Spree
expected_buckets(query.time_range, time_dim[:grain]).map { |bucket| [bucket] }
end
+ # Every bucket in the range becomes a row, so an absurd range is an
+ # absurd allocation: `last_500000_days`, or a `since` in the year one,
+ # would build millions of rows here and take the process down long
+ # before any of them reached a chart. Refused rather than trimmed —
+ # silently charting a different range than was asked for is worse.
def expected_buckets(range, grain)
from = range.first.in_time_zone(query.time_zone).to_date
to = range.last.in_time_zone(query.time_zone).to_date
+ span = (to - from).to_i + 1
+ if span > MAX_RANGE_DAYS
+ raise InvalidQuery,
+ "time_range covers #{span} days, more than the #{MAX_RANGE_DAYS} a single report may chart"
+ end
case grain
when :day then (from..to).map(&:to_s)
diff --git a/spree/core/lib/spree/reporting/default_vocabulary.rb b/spree/core/lib/spree/reporting/default_vocabulary.rb
index 7a0dc7f8d1..b93ff78833 100644
--- a/spree/core/lib/spree/reporting/default_vocabulary.rb
+++ b/spree/core/lib/spree/reporting/default_vocabulary.rb
@@ -136,10 +136,18 @@ module Spree
# A payment carries no completion timestamp, so it is anchored on
# when the row was created — near enough to when the money moved, and
# the only honest answer the schema can publish.
+ #
+ # The currency lives on the order, not the payment, but the money
+ # metrics here are formatted in one currency — so a store selling in
+ # several must filter by it, or a EUR payment and a USD payment are
+ # added together and the total labelled with whichever currency was
+ # asked for. `store.payments` is already `through: :orders`, so the
+ # join this reads is the association's own.
base :payments, family: :payments, table: '%{payments}',
time_column: '%{payments}.created_at',
- relation: lambda { |store, range, _currency|
- store.payments.where(created_at: range)
+ relation: lambda { |store, range, currency|
+ store.payments.where(Spree::Order.table_name => { currency: currency }).
+ where(Spree::Payment.table_name => { created_at: range })
}
# The movement table carries no store of its own; tenancy is the walk
diff --git a/spree/core/spec/lib/spree/reporting/query_spec.rb b/spree/core/spec/lib/spree/reporting/query_spec.rb
index 6114995fe2..39ea89185f 100644
--- a/spree/core/spec/lib/spree/reporting/query_spec.rb
+++ b/spree/core/spec/lib/spree/reporting/query_spec.rb
@@ -260,6 +260,26 @@ RSpec.describe Spree::Reporting::Query do
end
end
+ describe 'time range bounds' do
+ it 'refuses a range too wide to chart, however it was asked for' do
+ expect do
+ run(metrics: %w[orders], dimensions: [{ name: 'completed_at', grain: 'day' }],
+ time_range: { preset: 'last_500000_days' })
+ end.to raise_error(Spree::Reporting::InvalidQuery, /more than the/)
+
+ expect do
+ run(metrics: %w[orders], dimensions: [{ name: 'completed_at', grain: 'day' }],
+ time_range: { since: '0001-01-01', until: '2026-01-01' })
+ end.to raise_error(Spree::Reporting::InvalidQuery, /more than the/)
+ end
+
+ it 'still allows a range a merchant would plausibly read' do
+ result = run(metrics: %w[orders], dimensions: [{ name: 'completed_at', grain: 'month' }],
+ time_range: { preset: 'last_36_months' })
+ expect(result.rows.size).to eq(37)
+ end
+ end
+
describe 'the payments family' do
let!(:order) { create(:completed_order_with_totals, store: store, completed_at: 3.days.ago) }
let!(:payment) { create(:payment, order: order, amount: 30, status: 'completed') }
@@ -277,6 +297,17 @@ RSpec.describe Spree::Reporting::Query do
expect(after.totals[:net_payments][:value]).to eq(18.0)
end
+ # The currency lives on the order, and the totals are formatted in one
+ # currency — so a payment taken in another must not be added into them.
+ it 'counts only payments taken in the currency asked for' do
+ other = create(:completed_order_with_totals, store: store, currency: 'EUR', completed_at: 3.days.ago)
+ create(:payment, order: other, amount: 99, status: 'completed')
+
+ result = run(metrics: %w[payments_received payments_count])
+ expect(result.totals[:payments_received][:value]).to eq(30.0)
+ expect(result.totals[:payments_count][:value]).to eq(1)
+ end
+
it 'breaks payments down by the instrument that took them' do
result = run(metrics: %w[net_payments], dimensions: %w[payment_method])
expect(result.rows.first[:dimensions][:payment_method]).to eq(payment.payment_method_id)
diff --git a/spree/core/spec/models/spree/concerns/admin_user_methods_spec.rb b/spree/core/spec/models/spree/concerns/admin_user_methods_spec.rb
index 5b087f1bc4..7f025e4842 100644
--- a/spree/core/spec/models/spree/concerns/admin_user_methods_spec.rb
+++ b/spree/core/spec/models/spree/concerns/admin_user_methods_spec.rb
@@ -142,6 +142,13 @@ describe Spree::AdminUserMethods do
expect(created_order.reload.created_by_id).to be_nil
end
+ it 'nullifies the author on saved reports, which are store-wide and outlive them' do
+ report = create(:saved_report, store: current_store, user: admin_user)
+
+ admin_user.destroy
+ expect(report.reload.user_id).to be_nil
+ end
+
it 'nullifies created_by_id on gift cards' do
admin_user.destroy
expect(gift_card.reload.created_by_id).to be_nil