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.

Cover the generic record writes and the reporting tools

Damian Legawiec32f08a6b9f28
diff --git a/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb b/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb
new file mode 100644
index 0000000000..0a1ea0f4b7
--- /dev/null
+++ b/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb
@@ -0,0 +1,99 @@
+require 'spec_helper'
+
+# The reporting tools run the same queries the dashboard charts run, against
+# the same semantic registry, so an agent and a chart cannot disagree about
+# what a number means. What matters here is that the tools reach the registry,
+# stay compact, and refuse a member the caller may not reference.
+RSpec.describe 'agent reporting tools' do
+ let(:store) { @default_store }
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: scopes) }
+ let(:scopes) { ['read_all'] }
+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key) }
+
+ def tool(name)
+ Spree.agent_tools.available_for(context).find { |candidate| candidate.tool_name == name }
+ end
+
+ describe 'describe_reporting' do
+ it 'hands the model the real metric and dimension names' do
+ result = tool('describe_reporting').call
+
+ names = result[:metrics].map { |metric| metric[:name].to_s }
+
+ expect(names).to include('orders', 'net_sales')
+ expect(result[:dimensions]).to be_present
+ end
+
+ # A member the key cannot reference must not be offered, or the model
+ # composes a query it is then refused for.
+ context 'with a key that cannot read products' do
+ let(:scopes) { %w[read_reports read_orders] }
+
+ it 'leaves out the members that key could not query' do
+ offered = tool('describe_reporting').call[:metrics].map { |metric| metric[:name].to_s }
+ every = Spree.reporting.metrics.keys.map(&:to_s)
+
+ expect(offered).not_to match_array(every)
+ end
+ end
+ end
+
+ describe 'query_report' do
+ before { create(:completed_order_with_totals, store: store) }
+
+ it 'answers with totals' do
+ result = tool('query_report').call(metrics: ['orders'])
+
+ expect(result[:error]).to be_nil
+ expect(result.dig(:totals, 'orders', :value) || result.dig(:totals, :orders, :value)).to be_present
+ end
+
+ it 'groups by a dimension when asked' do
+ result = tool('query_report').call(metrics: ['orders'], dimensions: ['completed_at'])
+
+ expect(result[:error]).to be_nil
+ expect(result[:rows]).to be_an(Array)
+ end
+
+ # Rows land in the model's context verbatim, so a query that would return
+ # thousands is capped rather than filling the window.
+ it 'caps how many rows it will return' do
+ result = tool('query_report').call(metrics: ['orders'], dimensions: ['completed_at'], limit: 10_000)
+
+ expect(result[:error]).to be_nil
+ expect(result[:row_count]).to be <= Spree::AgentTools::QueryReport::MAX_LIMIT
+ end
+
+ # The registry's own rejection carries the valid names, so the model can
+ # correct itself instead of guessing again.
+ it 'names the valid members when given one that does not exist' do
+ result = tool('query_report').call(metrics: ['profit_margin_squared'])
+
+ expect(result[:error]).to be_present
+ expect(result[:valid]).to be_present
+ end
+
+ context 'with a key lacking the scope a member needs' do
+ let(:scopes) { %w[read_reports read_orders] }
+
+ it 'refuses rather than answering from data the key cannot see' do
+ product_metric = Spree.reporting.metrics.values.find { |metric| metric.key_scope == 'read_products' }
+ skip 'no product-scoped metric registered' if product_metric.nil?
+
+ result = tool('query_report').call(metrics: [product_metric.name.to_s])
+
+ expect(result[:error]).to be_present
+ end
+ end
+ end
+
+ describe 'what a key without read_reports is offered' do
+ let(:scopes) { ['read_products'] }
+
+ it 'is not offered the reporting tools' do
+ names = Spree.agent_tools.available_for(context).map(&:tool_name)
+
+ expect(names).not_to include('query_report', 'describe_reporting')
+ end
+ end
+end
diff --git a/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb b/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb
new file mode 100644
index 0000000000..778483869c
--- /dev/null
+++ b/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb
@@ -0,0 +1,115 @@
+require 'spec_helper'
+
+# The generic writes exist for the settings screens — the resources the Admin
+# API saves directly. Everything else is written by its own workflow tool, and
+# these have to say so rather than quietly doing it a second way.
+RSpec.describe 'agent generic record writes' do
+ let(:store) { @default_store }
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key) }
+
+ def tool(name)
+ Spree.agent_tools.available_for(context).find { |candidate| candidate.tool_name == name }
+ end
+
+ describe 'update_resource' do
+ let(:market) { store.markets.first || create(:market, store: store) }
+
+ it 'persists a change through the model\'s own validations' do
+ result = tool('update_resource').call(resource: 'markets', id: market.prefixed_id,
+ attributes: { 'name' => 'Northern Europe' })
+
+ expect(result[:error]).to be_nil
+ expect(market.reload.name).to eq('Northern Europe')
+ end
+
+ it 'hands back the model\'s own message when it refuses' do
+ result = tool('update_resource').call(resource: 'markets', id: market.prefixed_id,
+ attributes: { 'name' => '' })
+
+ expect(result[:error]).to be_present
+ expect(market.reload.name).not_to eq('')
+ end
+
+ # A resource with a workflow has exactly one way to be written, and the
+ # refusal names it so the model retries with the right tool instead of
+ # giving up.
+ it 'refuses a resource written through a workflow, naming its tool' do
+ product = create(:product, store: store)
+
+ result = tool('update_resource').call(resource: 'products', id: product.prefixed_id,
+ attributes: { 'name' => 'Renamed' })
+
+ expect(result[:error]).to include('products_update')
+ expect(product.reload.name).not_to eq('Renamed')
+ end
+
+ it 'refuses a resource written through a Tier 1 service' do
+ order = create(:order, store: store)
+
+ result = tool('update_resource').call(resource: 'orders', id: order.prefixed_id,
+ attributes: { 'email' => '[email protected]' })
+
+ expect(result[:error]).to be_present
+ end
+
+ # Silently dropping an attribute leaves the model believing it set
+ # something it did not; naming the real ones lets it correct itself.
+ it 'names the accepted attributes when given one it does not know' do
+ result = tool('update_resource').call(resource: 'markets', id: market.prefixed_id,
+ attributes: { 'colour' => 'blue' })
+
+ expect(result[:error]).to include('colour')
+ expect(result[:error]).to include('currency')
+ end
+
+ it 'does not reach another store\'s record' do
+ other = create(:market, store: create(:store, code: "other-#{SecureRandom.hex(4)}"))
+
+ result = tool('update_resource').call(resource: 'markets', id: other.prefixed_id,
+ attributes: { 'name' => 'Taken Over' })
+
+ expect(result[:error]).to be_present
+ expect(other.reload.name).not_to eq('Taken Over')
+ end
+
+ it 'refuses an unknown resource' do
+ result = tool('update_resource').call(resource: 'unicorns', id: 'x', attributes: {})
+
+ expect(result[:error]).to include('unicorns')
+ end
+ end
+
+ describe 'create_resource' do
+ # Built through the store's own association, so the record carries its
+ # tenancy from where it was built rather than from an attribute the caller
+ # could have named.
+ it 'creates the record in the caller\'s store' do
+ name = "Northern #{SecureRandom.hex(3)}"
+
+ result = tool('create_resource').call(
+ resource: 'markets',
+ attributes: { 'name' => name, 'currency' => 'EUR', 'default_locale' => 'en', 'country_codes' => ['DE'] }
+ )
+
+ expect(result[:error]).to be_nil
+ expect(Spree::Market.for_store(store).where(name: name)).to exist
+ end
+
+ it 'refuses a resource written through a workflow' do
+ result = tool('create_resource').call(resource: 'products', attributes: { 'name' => 'New' })
+
+ expect(result[:error]).to include('products_create')
+ end
+ end
+
+ describe 'what a read-only key is offered' do
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['read_all']) }
+
+ it 'is not offered the write tools at all' do
+ names = Spree.agent_tools.available_for(context).map(&:tool_name)
+
+ expect(names).not_to include('create_resource', 'update_resource', 'delete_resource')
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/create_resource.rb b/spree/core/app/tools/spree/agent_tools/create_resource.rb
index f966f98952..4c48aeb23a 100644
--- a/spree/core/app/tools/spree/agent_tools/create_resource.rb
+++ b/spree/core/app/tools/spree/agent_tools/create_resource.rb
@@ -23,6 +23,12 @@ module Spree
save_record(entry, record)
end
+ protected
+
+ def preferred_workflow_key(entry)
+ entry.create_workflow_key.presence || entry.update_workflow_key
+ end
+
private
# Built through the store's own association where there is one, so the
diff --git a/spree/core/app/tools/spree/agent_tools/query_report.rb b/spree/core/app/tools/spree/agent_tools/query_report.rb
index 89a49d74be..aa9fb31ef5 100644
--- a/spree/core/app/tools/spree/agent_tools/query_report.rb
+++ b/spree/core/app/tools/spree/agent_tools/query_report.rb
@@ -6,14 +6,15 @@ module Spree
# number means.
class QueryReport < Spree::AgentTool
tool_name 'query_report'
- description 'Run a reporting query: pick metrics (revenue, orders, units) and dimensions ' \
- '(time, product, channel, country) and get the aggregated rows. Call ' \
- 'describe_reporting first for the metrics and dimensions this store has.'
+ description 'Run a reporting query: pick metrics (net_sales, orders, units_sold) and ' \
+ 'dimensions to group them by, and get the aggregated rows. Call ' \
+ 'describe_reporting first for the exact names this store has.'
permission 'read_reports'
param :metrics, type: :array, description: 'Metric names, e.g. ["revenue", "orders"]', required: true
param :dimensions, type: :array,
- description: 'Dimensions to group by, e.g. ["time.month", "product"]. Omit for a single total.',
+ description: 'Dimensions to group by, as named by describe_reporting ' \
+ '(e.g. ["completed_at", "channel"]). Omit for a single total.',
required: false
param :time_range, type: :object,
description: 'A preset such as {"preset": "last_30_days"}, or {"from": "2026-01-01", "to": "2026-03-31"}',
diff --git a/spree/core/app/tools/spree/agent_tools/resource_write.rb b/spree/core/app/tools/spree/agent_tools/resource_write.rb
index 49eb3ee51a..67f0ba2b0d 100644
--- a/spree/core/app/tools/spree/agent_tools/resource_write.rb
+++ b/spree/core/app/tools/spree/agent_tools/resource_write.rb
@@ -49,13 +49,22 @@ module Spree
end
# A resource with a workflow is not written here — the tool that does it
- # is named, so the model retries correctly instead of giving up.
+ # is named, so the model retries correctly instead of giving up. Which
+ # tool depends on what was asked for: creating names the create
+ # workflow, changing and deleting name the update one.
def refusal_for(entry)
- workflow_key = entry.update_workflow_key || entry.create_workflow_key
- return "#{entry.key} cannot be changed with this tool." if workflow_key.blank?
+ workflow_key = preferred_workflow_key(entry)
- tool = workflow_key.tr('.', '_')
- "#{entry.key} is written through a workflow — use the #{tool} tool instead."
+ if workflow_key.blank?
+ return "#{entry.key} cannot be written with this tool — it is managed elsewhere in the dashboard."
+ end
+
+ "#{entry.key} is written through a workflow — use the #{workflow_key.tr('.', '_')} tool instead."
+ end
+
+ # Overridden by CreateResource, which wants the create workflow named.
+ def preferred_workflow_key(entry)
+ entry.update_workflow_key.presence || entry.create_workflow_key
end
# Only the attributes the Admin API itself would accept. Anything else is