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.

Changed the workflow tools to run through their endpoints

Damian Legawiecc141fb27ae19
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 510448c8b0..5f45eb47b5 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
@@ -148,4 +148,49 @@ RSpec.describe 'agent workflow tool arguments' do
expect(store.purchase_orders.last.created_by).to eq(admin)
end
end
+ # A workflow with an endpoint runs through it: the controller's routing,
+ # authentication, authorization and serializer, rather than a second copy
+ # of each beside them.
+ describe 'running through the endpoint' do
+ it 'dispatches every workflow that has one' do
+ in_process = Spree::AgentTools::DefaultCatalog::WORKFLOWS.reject do |key, _options|
+ Spree::AgentTools::WorkflowEndpoints.find(key)
+ end
+
+ # Only the product status moves, which the Admin API does not expose:
+ # `PATCH` writes the column and the bulk action uses `update_all`, so
+ # neither publishes the event nor withdraws an open submission.
+ expect(in_process.keys).to contain_exactly(
+ :product_activate_workflow, :product_draft_workflow, :product_archive_workflow
+ )
+ end
+
+ it 'fills a parent segment from the record the caller named' do
+ order = create(:order_with_line_items, store: store)
+ payment = create(:payment, order: order, amount: 10)
+
+ result = tool('payments_void').call(payment: payment.prefixed_id)
+
+ expect(result[:error]).to be_nil
+ expect(payment.reload.status).to eq('void')
+ end
+
+ it 'sends a keyword under the name the endpoint documents' do
+ order = create(:order_ready_to_ship, store: store)
+
+ result = tool('orders_cancel').call(order: order.prefixed_id, cancel_note: 'Duplicate order')
+
+ expect(result[:error]).to be_nil
+ expect(order.reload.status).to eq('canceled')
+ end
+
+ it 'does not reach a record in another store' do
+ theirs = create(:order_ready_to_ship, store: create(:store, code: "other-#{SecureRandom.hex(4)}"))
+
+ result = tool('orders_cancel').call(order: theirs.prefixed_id)
+
+ expect(result[:error]).to be_present
+ expect(theirs.reload.status).not_to eq('canceled')
+ end
+ end
end
diff --git a/spree/core/lib/spree/agent_tools/default_catalog.rb b/spree/core/lib/spree/agent_tools/default_catalog.rb
index 56cf2cc896..6a5f690711 100644
--- a/spree/core/lib/spree/agent_tools/default_catalog.rb
+++ b/spree/core/lib/spree/agent_tools/default_catalog.rb
@@ -54,10 +54,19 @@ module Spree
# Workflow key => permission, or => {permission:, except:, summary:}.
WORKFLOWS = {
# Catalog
+ #
+ # The three status moves below run in this process rather than through
+ # an endpoint, because the Admin API has none for them: `PATCH` writes
+ # the column and the bulk action uses `update_all`, so neither
+ # publishes the status event nor withdraws an open seller submission.
+ # They dispatch as soon as an admin status endpoint exists.
product_activate_workflow: 'write_products',
product_draft_workflow: 'write_products',
product_archive_workflow: 'write_products',
- product_approve_workflow: 'write_products',
+ # `note` and `auto` belong to the workflow, not to the endpoint: the
+ # review action passes neither, so offering them would describe a
+ # capability no caller has.
+ product_approve_workflow: { permission: 'write_products', except: %i[note auto] },
product_reject_workflow: 'write_products',
variant_create_workflow: 'write_products',
variant_update_workflow: 'write_products',
diff --git a/spree/core/lib/spree/agent_tools/workflow_tool.rb b/spree/core/lib/spree/agent_tools/workflow_tool.rb
index 93383a4f98..9c605e1078 100644
--- a/spree/core/lib/spree/agent_tools/workflow_tool.rb
+++ b/spree/core/lib/spree/agent_tools/workflow_tool.rb
@@ -169,6 +169,11 @@ module Spree
resolved = resolve_arguments(arguments)
return resolved if resolved.is_a?(Hash) && resolved[:error]
+ # The endpoint runs this workflow behind its own routing,
+ # authentication, authorization and serializer, so when there is one
+ # the request goes through it rather than beside it.
+ return dispatch(resolved) if endpoint
+
refusal = unauthorized_create || unauthorized_record(resolved)
return refusal if refusal
@@ -179,6 +184,13 @@ module Spree
{ error: e.message }
end
+ # @return [Spree::AgentTools::WorkflowEndpoints::Entry, nil]
+ def endpoint
+ return @endpoint if defined?(@endpoint)
+
+ @endpoint = WorkflowEndpoints.find(self.class.dependency_key)
+ end
+
# One line saying what this tool did, for the client's confirmation
# prompt and the assistant's approval card.
#
@@ -194,6 +206,94 @@ module Spree
private
+ # Runs the workflow by calling the operation that runs it.
+ #
+ # The path's `:id` is the record the write is about; a parent segment
+ # (`:order_id` on a payment) is read from that record rather than asked
+ # for, since the caller named the payment and the order follows from it.
+ # Everything else travels in the body under the name the endpoint
+ # documents, which is not always the workflow's keyword — a
+ # cancellation's `note:` is `cancel_note` on the wire.
+ def dispatch(resolved)
+ subject = subject_record(resolved)
+ path, missing = endpoint_path(subject, resolved)
+ return { error: missing } if missing
+
+ response = ApiDispatch.new(context).call(
+ method: endpoint.verb.downcase.to_sym, path: path, body: dispatch_body(resolved)
+ )
+ return { error: response.error_message } unless response.success?
+
+ { summary: summary(resolved, subject: subject),
+ record: payload_summary(response.data) }.compact
+ end
+
+ def endpoint_path(subject, resolved)
+ values = {}
+
+ endpoint.path_params.each do |segment|
+ record = segment == 'id' ? subject : parent_for(segment, subject, resolved)
+ return [nil, "This tool needs a #{segment.sub(/_id\z/, '').humanize.downcase} it was not given."] if
+ record.nil?
+
+ values[segment] = record.prefixed_id
+ end
+
+ [endpoint.path_for(values), nil]
+ end
+
+ # A parent segment names an association: `:order_id` on a payment is
+ # `payment.order`. A record the caller named for that association is
+ # preferred, so a split payment is refunded against the order the
+ # caller meant.
+ def parent_for(segment, subject, resolved)
+ name = segment.sub(/_id\z/, '')
+ named = resolved[name.to_sym]
+ return named if named.is_a?(ActiveRecord::Base)
+
+ subject.try(name)
+ end
+
+ # What the operation accepts, under its own names. A record resolved for
+ # a path segment is already in the path; anything else the endpoint does
+ # not document is left out rather than sent and ignored.
+ def dispatch_body(resolved)
+ accepted = endpoint.body_keys
+ return {} if accepted.empty?
+
+ resolved.each_with_object({}) do |(name, value), body|
+ key = body_key_for(name, accepted)
+ next if key.nil?
+
+ body[key] = value.is_a?(ActiveRecord::Base) ? value.prefixed_id : value
+ end
+ end
+
+ # The endpoint's name for a workflow keyword. Exact first, then the
+ # `_id` form a record takes on the wire, then a prefixed spelling —
+ # `note:` is `cancel_note` where the resource is what the prefix names.
+ def body_key_for(name, accepted)
+ candidates = [name.to_s, "#{name}_id", "#{subject_prefix}_#{name}", "#{subject_prefix}_#{name}_id"]
+
+ candidates.find { |candidate| accepted.include?(candidate) }
+ end
+
+ def subject_prefix
+ @subject_prefix ||= workflow_class.workflow_key.split('.').first.to_s.singularize
+ end
+
+ # A record as the endpoint returned it, summarised the way a record read
+ # from the map would be.
+ def payload_summary(data)
+ return unless data.is_a?(Hash)
+
+ entry = ResourceMap.all.find { |candidate| candidate.key == data['object'] } ||
+ subject_entry
+ return { id: data['id'] } if entry.nil?
+
+ RecordSummary.from_payload(entry: entry, payload: data)
+ end
+
# Holding `write_orders` says an admin may change orders; it does not say
# they may change *this* one. A host app narrows that with a
# record-level rule, the Admin API honours it, and a workflow tool must