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.

Removed the custom order creation tool

Damian Legawiecc51be1ce3137
diff --git a/docs/plans/6.0-mcp-server.md b/docs/plans/6.0-mcp-server.md
index 5127f44783..f55e14e341 100644
--- a/docs/plans/6.0-mcp-server.md
+++ b/docs/plans/6.0-mcp-server.md
@@ -615,9 +615,12 @@ record summary and context specs move from the assistant branch. New:
observed on the record). One such spec per workflow *family* (order,
fulfillment, return, product, price list), not per workflow — the
workflows have their own suites and the adapter is generic.
-- Generic record writes: an update on a market persists through validations;
- the same call on a product (which has a workflow) is refused and names
- `products_update`.
+- Generic record writes: an update on a market persists through validations,
+ and so does one on a product — the controller behind it declares the
+ workflow, so the generic write runs it. Ordinary create, update and
+ destroy therefore have no dedicated tool of their own; a resource whose
+ controller has no generic write (a variant, a fulfillment, a refund)
+ keeps one.
**API — contract specs (`spree_api`, where the controllers are).**
diff --git a/spree/api/lib/spree/api/agent_workflow_endpoints.rb b/spree/api/lib/spree/api/agent_workflow_endpoints.rb
new file mode 100644
index 0000000000..2a21d9f627
--- /dev/null
+++ b/spree/api/lib/spree/api/agent_workflow_endpoints.rb
@@ -0,0 +1,110 @@
+module Spree
+ module Api
+ # Which Admin API operation runs each workflow, derived rather than listed.
+ #
+ # Walk the admin routes; for each one, read the controller source and ask
+ # whether the action behind it calls that workflow. The verb and path come
+ # from the route, and the body keys from the generated OpenAPI document —
+ # which is the only place that records a rename (a cancellation's
+ # `reason:` keyword travels as `cancel_reason_id`).
+ #
+ # Read off the controllers for the same reason {AgentResourceMap} is: a
+ # workflow that gains an endpoint is dispatched without anyone editing a
+ # file, and one whose endpoint goes away stops being dispatched.
+ module AgentWorkflowEndpoints
+ # Where a controller declares a workflow for the base class to run,
+ # rather than calling it inside an action of its own.
+ DECLARED_IN = { 'create_workflow' => 'create', 'update_workflow' => 'update' }.freeze
+
+ class << self
+ # @param map [Module]
+ # @return [Integer] how many workflows were mapped
+ def install(map: Spree::AgentTools::WorkflowEndpoints)
+ map.reset!
+ keys = Spree::AgentTools::DefaultCatalog::WORKFLOWS.keys
+ document = openapi_document
+
+ admin_routes.each do |route|
+ source = controller_source(route[:controller])
+ next if source.nil?
+
+ keys.each do |key|
+ # `find` would derive, and deriving is what this is — read the
+ # entries already registered instead.
+ next if map.registered.key?(key)
+ next unless action_calling(source, key) == route[:action]
+
+ map.register(key: key, verb: route[:verb], path: route[:path],
+ body_keys: body_keys_for(document, route))
+ end
+ end
+
+ map.registered.size
+ end
+
+ private
+
+ def admin_routes
+ Spree::Core::Engine.routes.routes.filter_map do |route|
+ controller = route.defaults[:controller].to_s
+ next unless controller.start_with?('spree/api/v3/admin')
+
+ { controller: controller, action: route.defaults[:action].to_s,
+ verb: route.verb.to_s, path: route.path.spec.to_s.sub('(.:format)', '') }
+ end
+ end
+
+ # Which action calls this workflow: the `def` nearest above the call.
+ # A declaration consumed by the base class names the action it serves
+ # instead.
+ def action_calling(source, key)
+ index = source.index("Spree.#{key}")
+ return if index.nil?
+
+ enclosing = source[0...index].scan(/^\s+def ([a-z_]+)/).flatten.last
+ DECLARED_IN.fetch(enclosing, enclosing)
+ end
+
+ def controller_source(controller_path)
+ @sources ||= {}
+ return @sources[controller_path] if @sources.key?(controller_path)
+
+ @sources[controller_path] = begin
+ klass = "#{controller_path.camelize}Controller".safe_constantize
+ file = klass && Object.const_source_location(klass.name)&.first
+ file && File.exist?(file) ? File.read(file) : nil
+ rescue StandardError
+ nil
+ end
+ end
+
+ # What the operation's request body accepts, in the names the wire
+ # uses. A workflow keyword and its body key often differ, and the
+ # document is where that difference is recorded.
+ def body_keys_for(document, route)
+ operation = document.dig('paths', openapi_path(route[:path]), route[:verb].downcase)
+ schema = operation&.dig('requestBody', 'content', 'application/json', 'schema')
+
+ (schema&.dig('properties') || {}).keys
+ end
+
+ def openapi_path(path)
+ path.gsub(/:([a-z_]+)/) { "{#{Regexp.last_match(1)}}" }
+ end
+
+ # A packaged installation has no docs/ directory, and a body the
+ # document does not describe is simply passed through unchecked.
+ #
+ # `AgentWriteSchemas` already holds this file parsed, so it is read
+ # through there rather than a second time: the document is nearly a
+ # megabyte, and parsing it twice at boot is a second of nothing.
+ def openapi_document
+ Spree::Api::AgentWriteSchemas.document
+ rescue StandardError => e
+ Rails.logger.warn("[Spree] could not read the admin API document: #{e.class}: #{e.message}")
+ {}
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/lib/spree/api/agent_write_schemas.rb b/spree/api/lib/spree/api/agent_write_schemas.rb
index 6b5f3d056c..1e1a103122 100644
--- a/spree/api/lib/spree/api/agent_write_schemas.rb
+++ b/spree/api/lib/spree/api/agent_write_schemas.rb
@@ -41,6 +41,21 @@ module Spree
Spree::Api::Engine.root.join('..', '..', 'docs', 'api-reference', 'admin.yaml')
end
+ # The parsed document, for a reader that needs more of it than the
+ # write bodies — the workflow endpoint map wants the member actions'
+ # bodies too, and parsing a megabyte of YAML twice is wasteful.
+ #
+ # @return [Hash]
+ def document
+ @document ||= begin
+ path = spec_path
+ File.exist?(path) ? (YAML.unsafe_load_file(path) || {}) : {}
+ rescue StandardError => e
+ Rails.logger.warn("[Spree] could not read the admin API document: #{e.class}: #{e.message}")
+ {}
+ end
+ end
+
private
def schemas
diff --git a/spree/api/lib/spree/api/engine.rb b/spree/api/lib/spree/api/engine.rb
index 428dff8ea2..7c012b60b6 100644
--- a/spree/api/lib/spree/api/engine.rb
+++ b/spree/api/lib/spree/api/engine.rb
@@ -5,6 +5,7 @@ require_relative 'configuration'
require_relative 'agent_write_schemas'
require_relative 'agent_resource_map'
require_relative 'agent_membership_map'
+require_relative 'agent_workflow_endpoints'
require_relative 'oauth'
module Spree
diff --git a/spree/api/spec/integration/spree/api/v3/admin/seller_requirement_submissions_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/seller_requirement_submissions_spec.rb
new file mode 100644
index 0000000000..81b686fcb3
--- /dev/null
+++ b/spree/api/spec/integration/spree/api/v3/admin/seller_requirement_submissions_spec.rb
@@ -0,0 +1,140 @@
+# frozen_string_literal: true
+
+require 'swagger_helper'
+
+RSpec.describe 'Admin Seller Requirement Submissions API', type: :request,
+ swagger_doc: 'api-reference/admin.yaml' do
+ include_context 'API v3 Admin'
+
+ let(:Authorization) { "Bearer #{admin_jwt_token}" }
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:seller) { create(:seller, store: store) }
+ let(:requirement) { create(:attestation_requirement, store: store) }
+ let(:submission) { create(:seller_requirement_submission, seller: seller, requirement: requirement) }
+
+ path '/api/v3/admin/sellers/{seller_id}/requirement_submissions' do
+ parameter name: :seller_id, in: :path, type: :string, required: true, description: 'Seller prefixed ID'
+
+ post 'Waive a requirement for one seller' do
+ tags 'Sellers'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Excuses one seller from something the marketplace asks of everyone,
+ recording who decided and why. The seller's own branch is where a
+ seller submits; this is the operator setting a requirement aside.
+ DESC
+ admin_scope :write, :sellers
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ parameter name: :body, in: :body, schema: {
+ type: :object,
+ required: %w[requirement_id],
+ properties: {
+ requirement_id: { type: :string, description: 'The requirement being waived' },
+ review_note: { type: :string, description: 'Why it was waived',
+ example: 'Supplied under their parent company agreement.' }
+ }
+ }
+
+ response '201', 'requirement waived' do
+ let(:seller_id) { seller.prefixed_id }
+ let(:body) do
+ { requirement_id: requirement.prefixed_id,
+ review_note: 'Supplied under their parent company agreement.' }
+ end
+
+ schema '$ref' => '#/components/schemas/SellerRequirementSubmission'
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['status']).to eq('waived')
+ end
+ end
+
+ response '404', 'the requirement belongs to another store' do
+ let(:seller_id) { seller.prefixed_id }
+ let(:body) { { requirement_id: create(:attestation_requirement, store: create(:store)).prefixed_id } }
+
+ run_test!
+ end
+ end
+ end
+
+ path '/api/v3/admin/sellers/{seller_id}/requirement_submissions/{id}/accept' do
+ parameter name: :seller_id, in: :path, type: :string, required: true, description: 'Seller prefixed ID'
+ parameter name: :id, in: :path, type: :string, required: true, description: 'Submission prefixed ID'
+
+ patch 'Accept a submission' do
+ tags 'Sellers'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Passes what a seller sent in. A status moved by `PATCH` would skip
+ the mail and the extension hooks, so each decision is its own action.
+ DESC
+ admin_scope :write, :sellers
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ parameter name: :body, in: :body, required: false, schema: {
+ type: :object,
+ properties: {
+ review_note: { type: :string, description: 'A note kept with the decision' }
+ }
+ }
+
+ response '200', 'submission accepted' do
+ let(:seller_id) { seller.prefixed_id }
+ let(:id) { submission.prefixed_id }
+ let(:body) { {} }
+
+ schema '$ref' => '#/components/schemas/SellerRequirementSubmission'
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['status']).to eq('accepted')
+ end
+ end
+ end
+ end
+
+ path '/api/v3/admin/sellers/{seller_id}/requirement_submissions/{id}/reject' do
+ parameter name: :seller_id, in: :path, type: :string, required: true, description: 'Seller prefixed ID'
+ parameter name: :id, in: :path, type: :string, required: true, description: 'Submission prefixed ID'
+
+ patch 'Reject a submission' do
+ tags 'Sellers'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Turns down what a seller sent in. The note is what they act on, so it
+ travels with the decision.
+ DESC
+ admin_scope :write, :sellers
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ parameter name: :body, in: :body, required: false, schema: {
+ type: :object,
+ properties: {
+ review_note: { type: :string, example: 'Please send a clearer copy.' }
+ }
+ }
+
+ response '200', 'submission rejected' do
+ let(:seller_id) { seller.prefixed_id }
+ let(:id) { submission.prefixed_id }
+ let(:body) { { review_note: 'Please send a clearer copy.' } }
+
+ schema '$ref' => '#/components/schemas/SellerRequirementSubmission'
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['status']).to eq('rejected')
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/sellers_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/sellers_spec.rb
index 6701bcaf5d..29815575a4 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/sellers_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/sellers_spec.rb
@@ -392,6 +392,60 @@ RSpec.describe 'Admin Sellers API', type: :request, swagger_doc: 'api-reference/
end
end
+ path '/api/v3/admin/sellers/{id}/reopen_onboarding' do
+ parameter name: :id, in: :path, type: :string, required: true, description: 'Seller prefixed ID'
+
+ patch 'Send a seller back to onboarding' do
+ tags 'Sellers'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Hands an application back to the seller to finish, rather than
+ approving or rejecting it. Only a seller whose application is ready
+ for review can be sent back, and the note says what is missing.
+ DESC
+ admin_scope :write, :sellers
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ parameter name: :body, in: :body, required: false, schema: {
+ type: :object,
+ properties: {
+ note: { type: :string, description: 'What the seller still has to supply',
+ example: 'Your bank details do not match the registered business name.' }
+ }
+ }
+
+ response '200', 'seller back in onboarding' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:id) { seller.prefixed_id }
+ let(:body) { { note: 'Your bank details do not match the registered business name.' } }
+
+ before { seller.update!(status: 'ready_for_review') }
+
+ schema '$ref' => '#/components/schemas/Seller'
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['status']).to eq('onboarding')
+ end
+ end
+
+ response '422', 'the seller is not awaiting review' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:id) { seller.prefixed_id }
+ let(:body) { {} }
+
+ before { seller.update!(status: 'approved') }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+ end
+
path '/api/v3/admin/sellers/{id}/reject' do
parameter name: :id, in: :path, type: :string, required: true, description: 'Seller prefixed ID'
diff --git a/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb b/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb
index 4cd266b389..7adc60d31e 100644
--- a/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb
+++ b/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb
@@ -35,6 +35,18 @@ RSpec.describe 'assistant authorization' do
end
end
+
+ # Reads and edits every product, but may not bring one into existence or
+ # take one out of it — an ordinary shape for a catalog editor, and the one
+ # a write tool that only checked readability would ignore.
+ class NoCreateOrDestroyAbility < Spree::Ability
+ def initialize(user, options = {})
+ super
+ cannot :create, Spree::Product
+ cannot :destroy, Spree::Product
+ end
+ end
+
before do
RSpec.current_example.metadata[:hidden_product_id] = hidden.id
# `Spree.ability_class` is what the controller calls, and it answers a
@@ -118,16 +130,16 @@ RSpec.describe 'assistant authorization' do
end
it 'creates without demanding permission over the store or the actor' do
- tool = Spree.agent_tools.available_for(context).find { |t| t.tool_name == 'products_create' }
- result = tool.call(attributes: { 'name' => "Agent Made #{SecureRandom.hex(3)}" })
+ tool = Spree.agent_tools.available_for(context).find { |t| t.tool_name == 'create_resource' }
+ result = tool.call(resource: 'products', attributes: { 'name' => "Agent Made #{SecureRandom.hex(3)}" })
expect(result[:error]).to be_nil
expect(result.dig(:record, :title)).to start_with('Agent Made')
end
it 'names the created record in the summary, not the store' do
- tool = Spree.agent_tools.available_for(context).find { |t| t.tool_name == 'products_create' }
- result = tool.call(attributes: { 'name' => 'Summary Subject' })
+ tool = Spree.agent_tools.available_for(context).find { |t| t.tool_name == 'create_resource' }
+ result = tool.call(resource: 'products', attributes: { 'name' => 'Summary Subject' })
expect(result[:summary]).to include('Summary Subject')
expect(result[:summary]).not_to include(store.name)
@@ -139,25 +151,15 @@ RSpec.describe 'assistant authorization' do
# before calling the workflow, and the tool has no equivalent unless it
# authorizes against the class.
context 'when the admin may edit products but not create one' do
- let(:ability) do
- Class.new do
- include CanCan::Ability
-
- def initialize(*)
- can :read, Spree::Product
- can :update, Spree::Product
- end
-
- def permission_keys
- Spree.permissions.catalog_keys
- end
- end.new
+ before do
+ allow(Spree).to receive(:ability_class).and_return(NoCreateOrDestroyAbility)
+ allow(Spree::Dependencies).to receive(:ability_class).and_return('NoCreateOrDestroyAbility')
end
it 'refuses the create workflow' do
create_tool = Spree.agent_tools.available_for(context).
- find { |candidate| candidate.tool_name == 'products_create' }
- result = create_tool.call(attributes: { 'name' => 'Should Not Exist' })
+ find { |candidate| candidate.tool_name == 'create_resource' }
+ result = create_tool.call(resource: 'products', attributes: { 'name' => 'Should Not Exist' })
expect(result[:error]).to be_present
expect(Spree::Product.for_store(store).where(name: 'Should Not Exist')).not_to exist
@@ -169,25 +171,15 @@ RSpec.describe 'assistant authorization' do
# without `:destroy` means it. A deletion checked as an update would go
# straight through.
context 'when the admin may edit a product but not delete one' do
- let(:ability) do
- Class.new do
- include CanCan::Ability
-
- def initialize(*)
- can :read, Spree::Product
- can :update, Spree::Product
- end
-
- def permission_keys
- Spree.permissions.catalog_keys
- end
- end.new
+ before do
+ allow(Spree).to receive(:ability_class).and_return(NoCreateOrDestroyAbility)
+ allow(Spree::Dependencies).to receive(:ability_class).and_return('NoCreateOrDestroyAbility')
end
it 'refuses the destroy workflow' do
destroy = Spree.agent_tools.available_for(context).
- find { |candidate| candidate.tool_name == 'products_destroy' }
- result = destroy.call(product: visible.prefixed_id)
+ find { |candidate| candidate.tool_name == 'delete_resource' }
+ result = destroy.call(resource: 'products', id: visible.prefixed_id)
expect(result[:error]).to be_present
expect(visible.reload).to be_present
diff --git a/spree/api/spec/tools/spree/agent_tools/create_order_spec.rb b/spree/api/spec/tools/spree/agent_tools/create_order_spec.rb
deleted file mode 100644
index f7069612fa..0000000000
--- a/spree/api/spec/tools/spree/agent_tools/create_order_spec.rb
+++ /dev/null
@@ -1,115 +0,0 @@
-require 'spec_helper'
-
-# Cancelling and completing an order reach an agent through the workflow
-# allowlist. Creating one is a service, so it is a written tool — and the gap
-# showed up in use: an agent could make the customer but not the order.
-RSpec.describe 'agent draft order creation' 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, request_headers: agent_headers_for_key(api_key)) }
- let(:product) { create(:product, store: store, status: 'active') }
- let(:variant) { product.variants.first || create(:variant, product: product) }
-
- def tool(ctx = context)
- Spree.agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == 'orders_create' }
- end
-
- describe 'creating one' do
- it 'leaves a draft for the merchant to review' do
- result = tool.call(email: '[email protected]',
- items: [{ variant_id: variant.prefixed_id, quantity: 3 }])
-
- expect(result[:error]).to be_nil
- expect(result[:status]).to eq('draft')
- expect(result[:item_count]).to eq(3)
-
- order = store.orders.find_by_prefix_id(result[:id])
- expect(order.line_items.sum(&:quantity)).to eq(3)
- expect(order.email).to eq('[email protected]')
- end
-
- it 'orders for an existing customer' do
- customer = create(:customer)
-
- result = tool.call(customer_id: customer.prefixed_id,
- items: [{ variant_id: variant.prefixed_id, quantity: 1 }])
-
- expect(result[:error]).to be_nil
- expect(store.orders.find_by_prefix_id(result[:id]).customer).to eq(customer)
- end
-
- # Who asked matters later, on the order's own record.
- it 'records the credential that asked as the creator' do
- result = tool.call(email: '[email protected]', items: [{ variant_id: variant.prefixed_id }])
-
- expect(store.orders.find_by_prefix_id(result[:id]).created_by).to eq(api_key)
- end
-
- it 'defaults a line with no quantity to one' do
- result = tool.call(email: '[email protected]', items: [{ variant_id: variant.prefixed_id }])
-
- expect(result[:item_count]).to eq(1)
- end
- end
-
- # The mistake a model makes most: a product has variants, and only a variant
- # can be ordered. Answering with the choices is what lets it correct itself
- # in one step instead of asking the merchant.
- describe 'given a product where a variant belongs' do
- it 'names the variants to choose between' do
- create(:variant, product: product)
-
- result = tool.call(email: '[email protected]', items: [{ variant_id: product.prefixed_id }])
-
- expect(result[:error]).to include('is a product')
- expect(result[:variants].map { |v| v[:id] }).to match_array(product.variants.map(&:prefixed_id))
- end
- end
-
- describe 'refusals' do
- it 'needs someone to order for' do
- expect(tool.call(items: [{ variant_id: variant.prefixed_id }])[:error]).to include('customer_id or an email')
- end
-
- it 'needs at least one item' do
- expect(tool.call(email: '[email protected]', items: [])[:error]).to include('at least one item')
- end
-
- it 'needs a variant on every line' do
- expect(tool.call(email: '[email protected]', items: [{ quantity: 2 }])[:error]).to include('needs a variant_id')
- end
-
- it 'refuses an unknown customer' do
- expect(tool.call(customer_id: 'cust_nope', items: [{ variant_id: variant.prefixed_id }])[:error]).
- to include('No customer found')
- end
-
- # Another store's variant is not orderable here, so it is not found rather
- # than quietly ordered.
- it 'cannot order a variant belonging to another store' do
- theirs = create(:product, store: create(:store, code: "other-#{SecureRandom.hex(4)}"), status: 'active')
-
- result = tool.call(email: '[email protected]', items: [{ variant_id: theirs.variants.first.prefixed_id }])
-
- expect(result[:error]).to include('No variant found')
- expect(store.orders.where(email: '[email protected]')).to be_empty
- end
-
- it 'is withheld from a caller who may only read orders' do
- read_only = create(:api_key, :secret, store: store, scopes: ['read_orders'])
-
- expect(tool(Spree::AgentTools::Context.new(store: store, api_key: read_only, request_headers: agent_headers_for_key(read_only)))).to be_nil
- end
-
- # The service's own refusal, in its words — a draft product cannot be sold,
- # and the merchant needs to know which rule stopped it.
- it 'passes on why the order could not be created' do
- draft = create(:product, store: store, status: 'draft')
-
- result = tool.call(email: '[email protected]', items: [{ variant_id: draft.variants.first.prefixed_id }])
-
- expect(result[:error]).to be_present
- expect(result[:ok]).to be_nil
- end
- end
-end
diff --git a/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb b/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb
index de390451af..510448c8b0 100644
--- a/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb
+++ b/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb
@@ -17,29 +17,36 @@ RSpec.describe 'agent workflow tool arguments' do
let(:stock_location) { store.stock_locations.first || create(:stock_location, store: store) }
let(:variant) { create(:variant) }
- # A purchase order's `items:` names a variant per row. Left as a string
- # the association is handed a prefixed id and the record fails with
- # "must exist", which reads to the model as a bad id rather than a step
- # the tool skipped.
+ # A purchase order's items name a variant per row. The ids inside those
+ # rows have to be decoded too, not just the ones at the top level.
it 'resolves them to records' do
- result = tool('purchase_orders_create').call(
- supplier: supplier.prefixed_id,
- destination_location: stock_location.prefixed_id,
- items: [{ 'variant' => variant.prefixed_id, 'quantity_ordered' => 2, 'unit_cost' => 5 }]
+ result = tool('create_resource').call(
+ resource: 'purchase_orders',
+ attributes: {
+ 'supplier_id' => supplier.prefixed_id,
+ 'destination_location_id' => stock_location.prefixed_id,
+ 'items' => [{ 'variant_id' => variant.prefixed_id, 'quantity_ordered' => 2,
+ 'unit_cost' => '5.00' }]
+ }
)
expect(result[:error]).to be_nil
expect(store.purchase_orders.last.items.first.variant).to eq(variant)
end
- it 'names the row and the field when an id matches nothing' do
- result = tool('purchase_orders_create').call(
- supplier: supplier.prefixed_id,
- destination_location: stock_location.prefixed_id,
- items: [{ 'variant' => 'variant_nope', 'quantity_ordered' => 1, 'unit_cost' => 1 }]
+ it 'names what was not found when an id inside a row matches nothing' do
+ result = tool('create_resource').call(
+ resource: 'purchase_orders',
+ attributes: {
+ 'supplier_id' => supplier.prefixed_id,
+ 'destination_location_id' => stock_location.prefixed_id,
+ 'items' => [{ 'variant_id' => 'variant_nope', 'quantity_ordered' => 1,
+ 'unit_cost' => '1.00' }]
+ }
)
- expect(result[:error]).to include('variant', 'items')
+ expect(result[:error]).to include('Variant')
+ expect(store.purchase_orders).to be_empty
end
end
@@ -54,8 +61,8 @@ RSpec.describe 'agent workflow tool arguments' do
let(:other_store) { create(:store) }
it 'is refused by name on create rather than written' do
- result = tool('products_create').call(
- attributes: { 'name' => 'Tenancy probe', 'store_id' => other_store.id }
+ result = tool('create_resource').call(
+ resource: 'products', attributes: { 'name' => 'Tenancy probe', 'store_id' => other_store.id }
)
expect(result[:error]).to include('store_id')
@@ -67,8 +74,8 @@ RSpec.describe 'agent workflow tool arguments' do
it 'cannot move an existing record to another store' do
product = create(:product, store: store)
- result = tool('products_update').call(
- product: product.prefixed_id, attributes: { 'store_id' => other_store.id }
+ result = tool('update_resource').call(
+ resource: 'products', id: product.prefixed_id, attributes: { 'store_id' => other_store.id }
)
expect(result[:error]).to include('store_id')
@@ -107,10 +114,14 @@ RSpec.describe 'agent workflow tool arguments' do
let(:variant) { create(:variant) }
it 'leaves it unset rather than failing the call' do
- result = tool('purchase_orders_create').call(
- supplier: supplier.prefixed_id,
- destination_location: stock_location.prefixed_id,
- items: [{ 'variant' => variant.prefixed_id, 'quantity_ordered' => 1, 'unit_cost' => 3 }]
+ result = tool('create_resource').call(
+ resource: 'purchase_orders',
+ attributes: {
+ 'supplier_id' => supplier.prefixed_id,
+ 'destination_location_id' => stock_location.prefixed_id,
+ 'items' => [{ 'variant_id' => variant.prefixed_id, 'quantity_ordered' => 1,
+ 'unit_cost' => '3.00' }]
+ }
)
expect(result[:error]).to be_nil
@@ -121,12 +132,16 @@ RSpec.describe 'agent workflow tool arguments' do
admin = create(:admin_user)
admin_context = Spree::AgentTools::Context.new(store: store, user: admin, request_headers: agent_headers_for(admin))
admin_tool = Spree.agent_tools.available_for(admin_context).
- find { |candidate| candidate.tool_name == 'purchase_orders_create' }
+ find { |candidate| candidate.tool_name == 'create_resource' }
result = admin_tool.call(
- supplier: supplier.prefixed_id,
- destination_location: stock_location.prefixed_id,
- items: [{ 'variant' => variant.prefixed_id, 'quantity_ordered' => 1, 'unit_cost' => 3 }]
+ resource: 'purchase_orders',
+ attributes: {
+ 'supplier_id' => supplier.prefixed_id,
+ 'destination_location_id' => stock_location.prefixed_id,
+ 'items' => [{ 'variant_id' => variant.prefixed_id, 'quantity_ordered' => 1,
+ 'unit_cost' => '3.00' }]
+ }
)
expect(result[:error]).to be_nil
diff --git a/spree/core/app/tools/spree/agent_tools/create_order.rb b/spree/core/app/tools/spree/agent_tools/create_order.rb
deleted file mode 100644
index 5b65c2e407..0000000000
--- a/spree/core/app/tools/spree/agent_tools/create_order.rb
+++ /dev/null
@@ -1,139 +0,0 @@
-module Spree
- module AgentTools
- # Starts a draft order for a customer, with the lines it should hold.
- #
- # Cancelling and completing an order are workflows, so they reach an agent
- # through the workflow allowlist. Creating one is a service — the admin
- # create takes customer, items, addresses and a coupon in a single call —
- # so it is written out here rather than derived.
- #
- # A draft, never a placed order: the merchant reviews it, and completing
- # it is `orders_complete`, its own decision with its own approval.
- class CreateOrder < Spree::AgentTool
- tool_name 'orders_create'
- description 'Start a draft order for a customer, with the items it should hold. ' \
- 'Items name a variant, not a product — search variants to pick one when ' \
- 'a product has several. The order is left as a draft for the merchant to ' \
- 'review; completing it is a separate step.'
- permission 'write_orders'
- mutating!
-
- param :customer_id, description: "The customer's prefixed id. Either this or email is required."
- param :email, description: 'Email of the person ordering, when they are not an existing customer'
- param :items, type: :array, items: :object, required: true,
- description: 'Lines to order: [{"variant_id": "variant_k5nR8xLq", "quantity": 3}]'
- param :currency, description: "Three-letter code; the store's own currency when omitted"
- param :customer_note, description: 'A note the merchant wants kept on the order'
-
- def call(items:, customer_id: nil, email: nil, currency: nil, customer_note: nil)
- return { error: 'Give either a customer_id or an email.' } if customer_id.blank? && email.blank?
-
- customer = nil
- if customer_id.present?
- customer = find_customer(customer_id)
- return { error: "No customer found for #{customer_id.inspect}." } if customer.nil?
- end
-
- lines, refusal = resolve_items(items)
- return refusal if refusal
-
- create(customer: customer, email: email, lines: lines, currency: currency, note: customer_note)
- end
-
- def summary(arguments)
- count = Array(arguments[:items]).sum { |item| (item[:quantity] || item['quantity'] || 1).to_i }
- who = arguments[:email].presence || arguments[:customer_id]
-
- "Create a draft order for #{who} with #{count} #{'item'.pluralize(count)}"
- end
-
- private
-
- def create(customer:, email:, lines:, currency:, note:)
- result = Spree.order_create_service.call(
- store: context.store,
- customer: customer,
- created_by: context.principal,
- params: {
- email: email.presence || customer&.email,
- currency: currency.presence,
- customer_note: note.presence,
- items: lines
- }.compact
- )
-
- return { error: failure_message(result) } unless result.success?
-
- order = result.value
- {
- ok: true,
- id: order.prefixed_id,
- number: order.number,
- status: order.status,
- item_count: order.line_items.sum(&:quantity),
- total: order.display_total.to_s,
- dashboard_path: ResourceMap.find('orders')&.dashboard_path_for(order)
- }
- end
-
- # A product has variants, and only a variant can be ordered. Naming the
- # product instead is the mistake a model makes most here, so it is
- # answered with the variants to choose between rather than a refusal
- # the model cannot act on.
- def resolve_items(items)
- rows = Array(items).map { |item| item.respond_to?(:to_h) ? item.to_h.symbolize_keys : {} }
- return [nil, { error: 'Give at least one item.' }] if rows.empty?
-
- resolved = rows.map do |row|
- id = row[:variant_id].presence
- return [nil, { error: 'Every item needs a variant_id.' }] if id.blank?
-
- variant = find_variant(id)
- return [nil, variant_refusal(id)] if variant.nil?
-
- { variant_id: variant.id, quantity: [(row[:quantity] || 1).to_i, 1].max }
- end
-
- [resolved, nil]
- end
-
- def find_customer(id)
- context.accessible(Spree.customer_class.for_store(context.store), :show).find_by_prefix_id(id)
- rescue StandardError
- nil
- end
-
- def find_variant(id)
- context.accessible(Spree::Variant.for_store(context.store), :show).find_by_prefix_id(id)
- rescue StandardError
- nil
- end
-
- # Where the id names a product, list its variants: that is the one extra
- # step the model needs, and it already has permission to read them.
- def variant_refusal(id)
- product = begin
- context.accessible(Spree::Product.for_store(context.store), :show).find_by_prefix_id(id)
- rescue StandardError
- nil
- end
- return { error: "No variant found for #{id.inspect}." } if product.nil?
-
- {
- error: "#{id.inspect} is a product, and an order holds variants. " \
- "#{product.name} has #{product.variants.count} to choose from.",
- variants: product.variants.map do |variant|
- { id: variant.prefixed_id, label: variant.options_text.presence || variant.sku }
- end
- }
- end
-
- def failure_message(result)
- error = result.error
- message = error.try(:value).is_a?(String) ? error.value : error.to_s
-
- message.presence || 'The order could not be created.'
- end
- end
- end
-end
diff --git a/spree/core/lib/spree/agent_tools.rb b/spree/core/lib/spree/agent_tools.rb
index 032bc9a6fc..ce5caf1ad4 100644
--- a/spree/core/lib/spree/agent_tools.rb
+++ b/spree/core/lib/spree/agent_tools.rb
@@ -4,6 +4,7 @@ require 'spree/agent_tools/resource_map'
require 'spree/agent_tools/attachment_registry'
require 'spree/agent_tools/api_dispatch'
require 'spree/agent_tools/membership_map'
+require 'spree/agent_tools/workflow_endpoints'
require 'spree/agent_tools/record_summary'
require 'spree/agent_tools/workflow_schema'
require 'spree/agent_tools/workflow_tool'
diff --git a/spree/core/lib/spree/agent_tools/default_catalog.rb b/spree/core/lib/spree/agent_tools/default_catalog.rb
index b4a1148753..56cf2cc896 100644
--- a/spree/core/lib/spree/agent_tools/default_catalog.rb
+++ b/spree/core/lib/spree/agent_tools/default_catalog.rb
@@ -21,7 +21,6 @@ module Spree
Spree::AgentTools::DeleteResource
Spree::AgentTools::CurateProducts
Spree::AgentTools::UploadFile
- Spree::AgentTools::CreateOrder
Spree::AgentTools::CreateMedia
Spree::AgentTools::CreateImport
Spree::AgentTools::SetStock
@@ -55,9 +54,6 @@ module Spree
# Workflow key => permission, or => {permission:, except:, summary:}.
WORKFLOWS = {
# Catalog
- product_create_workflow: 'write_products',
- product_update_workflow: 'write_products',
- product_destroy_workflow: 'write_products',
product_activate_workflow: 'write_products',
product_draft_workflow: 'write_products',
product_archive_workflow: 'write_products',
@@ -65,12 +61,8 @@ module Spree
product_reject_workflow: 'write_products',
variant_create_workflow: 'write_products',
variant_update_workflow: 'write_products',
- catalog_create_workflow: 'write_products',
- catalog_update_workflow: 'write_products',
catalog_activate_workflow: 'write_products',
catalog_deactivate_workflow: 'write_products',
- price_list_create_workflow: 'write_products',
- price_list_update_workflow: 'write_products',
price_list_activate_workflow: 'write_products',
price_list_deactivate_workflow: 'write_products',
@@ -92,8 +84,6 @@ module Spree
refund_create_workflow: 'write_refunds',
# Inventory
- stock_transfer_create_workflow: 'write_stock',
- stock_transfer_update_workflow: 'write_stock',
stock_transfer_mark_ready_workflow: 'write_stock',
stock_transfer_mark_in_transit_workflow: 'write_stock',
stock_transfer_receive_workflow: 'write_stock',
@@ -102,8 +92,6 @@ module Spree
stock_transfer_close_workflow: 'write_stock',
# Purchasing
- purchase_order_create_workflow: 'write_purchasing',
- purchase_order_update_workflow: 'write_purchasing',
purchase_order_mark_ordered_workflow: 'write_purchasing',
purchase_order_receive_workflow: 'write_purchasing',
purchase_order_cancel_workflow: 'write_purchasing',
@@ -111,7 +99,6 @@ module Spree
purchase_order_close_workflow: 'write_purchasing',
# Marketplace
- seller_create_workflow: 'write_sellers',
seller_invite_workflow: 'write_sellers',
seller_approve_workflow: 'write_sellers',
seller_reject_workflow: 'write_sellers',
@@ -136,7 +123,27 @@ module Spree
'A step of the dashboard\'s email template editor, which drafts and previews against a ' \
'live rendering. Publishing sends real mail in the merchant\'s name.'.freeze
+ # Plain create, update and destroy reach these through the generic write
+ # tools, which dispatch to the controller — and the controller declares
+ # this very workflow, so both paths run the same code. Two tools for one
+ # job only cost a model a choice it has no basis to make.
+ GENERIC_WRITE_REASON =
+ 'Ordinary CRUD: the generic create, update and destroy tools dispatch to the controller, ' \
+ 'which declares this workflow, so exposing it again would be a second path to the same code.'
+
EXCLUDED_WORKFLOWS = {
+ product_create_workflow: GENERIC_WRITE_REASON,
+ product_update_workflow: GENERIC_WRITE_REASON,
+ product_destroy_workflow: GENERIC_WRITE_REASON,
+ catalog_create_workflow: GENERIC_WRITE_REASON,
+ catalog_update_workflow: GENERIC_WRITE_REASON,
+ price_list_create_workflow: GENERIC_WRITE_REASON,
+ price_list_update_workflow: GENERIC_WRITE_REASON,
+ stock_transfer_create_workflow: GENERIC_WRITE_REASON,
+ stock_transfer_update_workflow: GENERIC_WRITE_REASON,
+ purchase_order_create_workflow: GENERIC_WRITE_REASON,
+ purchase_order_update_workflow: GENERIC_WRITE_REASON,
+ seller_create_workflow: GENERIC_WRITE_REASON,
email_template_save_draft_workflow: EMAIL_TEMPLATE_EDITOR_REASON,
email_template_publish_workflow: EMAIL_TEMPLATE_EDITOR_REASON,
email_template_discard_draft_workflow: EMAIL_TEMPLATE_EDITOR_REASON,
diff --git a/spree/core/lib/spree/agent_tools/workflow_endpoints.rb b/spree/core/lib/spree/agent_tools/workflow_endpoints.rb
new file mode 100644
index 0000000000..d24479f006
--- /dev/null
+++ b/spree/core/lib/spree/agent_tools/workflow_endpoints.rb
@@ -0,0 +1,88 @@
+module Spree
+ module AgentTools
+ # Which Admin API operation runs each workflow an agent may call.
+ #
+ # A contract like {ResourceMap} and {MembershipMap}: core declares the
+ # shape, and `spree_api` fills it by reading its own routes and
+ # controllers, so a workflow that gains an endpoint is dispatched without
+ # anyone editing a list.
+ #
+ # A workflow with no entry runs in this process instead. That is not a
+ # fallback to be relied on — it means the capability has no endpoint yet,
+ # and the tool is the only way to reach it.
+ module WorkflowEndpoints
+ # @!attribute verb
+ # @return [String] 'POST', 'PATCH'
+ # @!attribute path
+ # @return [String] with `:name` segments still in it
+ # @!attribute body_keys
+ # @return [Array<String>] what the operation's request body accepts,
+ # read from the generated OpenAPI document — which is where the
+ # renames live (a cancellation's `reason:` keyword is
+ # `cancel_reason_id` on the wire)
+ Entry = Struct.new(:verb, :path, :body_keys, keyword_init: true) do
+ # The dynamic segments, in the order the path names them.
+ #
+ # @return [Array<String>]
+ def path_params
+ @path_params ||= path.scan(/:([a-z_]+)/).flatten
+ end
+
+ # @param values [Hash] path parameter name => id
+ # @return [String]
+ def path_for(values)
+ path.gsub(/:([a-z_]+)/) { values.fetch(Regexp.last_match(1)).to_s }
+ end
+ end
+
+ class << self
+ # @param key [Symbol] a `Spree::Dependencies` workflow key
+ # @return [Entry, nil]
+ def find(key)
+ derive!
+ entries[key.to_sym]
+ end
+
+ # @return [Hash{Symbol => Entry}]
+ def all
+ derive!
+ entries
+ end
+
+ def register(key:, verb:, path:, body_keys: [])
+ entries[key.to_sym] = Entry.new(verb: verb.to_s.upcase, path: path,
+ body_keys: body_keys.map(&:to_s))
+ end
+
+ def reset!
+ @entries = {}
+ @derived = false
+ end
+
+ # What has been registered so far, without deriving — for the
+ # deriver itself, which must not ask for what it is producing.
+ #
+ # @return [Hash{Symbol => Entry}]
+ def registered
+ entries
+ end
+
+ # Filled on first read rather than at boot: deriving it loads every
+ # admin controller, which a developer who never runs an agent should
+ # not pay for on each code reload.
+ def derive!
+ return if @derived
+
+ @derived = true
+ Spree::Api::AgentWorkflowEndpoints.install if defined?(Spree::Api::AgentWorkflowEndpoints)
+ end
+
+ private
+
+ def entries
+ @entries ||= {}
+ end
+ end
+ end
+ end
+end
diff --git a/spree/mcp/spec/lib/spree/mcp/server_spec.rb b/spree/mcp/spec/lib/spree/mcp/server_spec.rb
index 89d453ee9f..7b6f403a75 100644
--- a/spree/mcp/spec/lib/spree/mcp/server_spec.rb
+++ b/spree/mcp/spec/lib/spree/mcp/server_spec.rb
@@ -76,7 +76,7 @@ RSpec.describe Spree::Mcp::Server do
let(:scopes) { ['write_products'] }
it 'offers that resource\'s workflow tools' do
- expect(names).to include('products_update', 'products_activate')
+ expect(names).to include('products_activate', 'products_draft')
end
it 'offers no other resource\'s write tools' do
@@ -104,7 +104,7 @@ RSpec.describe Spree::Mcp::Server do
it 'never offers the principal or the store as a parameter' do
cancel = tools.find { |tool| tool['name'] == 'orders_cancel' }
- create = tools.find { |tool| tool['name'] == 'products_create' }
+ create = tools.find { |tool| tool['name'] == 'variants_create' }
expect(cancel.dig('inputSchema', 'properties')).not_to have_key('canceler')
expect(create.dig('inputSchema', 'properties')).not_to have_key('store')