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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: records named inside a list of rows were never resolved
Damian Legawiec491d0ad8a8da
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.rbnew file mode 100644index 0000000000..976959be4f--- /dev/null+++ b/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb@@ -0,0 +1,82 @@+require 'spec_helper'++# A workflow tool's arguments arrive as JSON, so every record it is meant to+# act on comes in as a prefixed id. What the tool does between receiving those+# strings and calling the workflow is the whole of its contract.+RSpec.describe 'agent workflow tool arguments' 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 'records named inside a list of rows' do+ let(:supplier) { create(:supplier, store: store) }+ 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.+ 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 }]+ )++ 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 }]+ )++ expect(result[:error]).to include('variant', 'items')+ end+ end++ # Several models still declare `created_by` as a plain belongs_to on the+ # admin-user class rather than through `acted_by`. Handing one an API key+ # raises inside the workflow, where the honest outcome is an unattributed+ # record.+ describe 'an actor the record cannot hold' do+ let(:supplier) { create(:supplier, store: store) }+ let(:stock_location) { store.stock_locations.first || create(:stock_location, store: store) }+ 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 }]+ )++ expect(result[:error]).to be_nil+ expect(store.purchase_orders.last.created_by).to be_nil+ end++ it 'records an admin user, which the association does accept' do+ admin = create(:admin_user)+ admin_context = Spree::AgentTools::Context.new(store: store, user: admin)+ admin_tool = Spree.agent_tools.available_for(admin_context).+ find { |candidate| candidate.tool_name == 'purchase_orders_create' }++ 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 }]+ )++ expect(result[:error]).to be_nil+ expect(store.purchase_orders.last.created_by).to eq(admin)+ end+ end+enddiff --git a/spree/core/app/tools/spree/agent_tools/delete_resource.rb b/spree/core/app/tools/spree/agent_tools/delete_resource.rbindex 9cae340ac6..a3bdd804fe 100644--- a/spree/core/app/tools/spree/agent_tools/delete_resource.rb+++ b/spree/core/app/tools/spree/agent_tools/delete_resource.rb@@ -25,6 +25,20 @@ module Spree{ error: record.errors.full_messages.to_sentence.presence || "#{label} could not be deleted." }endend+ protected++ # A delete has no workflow key of its own in the map, so naming the+ # update workflow would send the model to a tool that cannot delete.+ # The refusal points at the resource's workflow family instead and+ # lets `describe_resource` list what is actually callable.+ def refusal_for(entry)+ family = entry.update_workflow_key.presence || entry.create_workflow_key+ return super if family.blank?++ "#{entry.key} is written through workflows — call describe_resource to see " \+ "which #{family.split('.').first}_* tool removes one."+ end+endendenddiff --git a/spree/core/app/tools/spree/agent_tools/resource_write.rb b/spree/core/app/tools/spree/agent_tools/resource_write.rbindex 5d6b231290..2457262ca5 100644--- a/spree/core/app/tools/spree/agent_tools/resource_write.rb+++ b/spree/core/app/tools/spree/agent_tools/resource_write.rb@@ -48,10 +48,10 @@ module Spree[entry, nil]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. Which- # tool depends on what was asked for: creating names the create- # workflow, changing and deleting name the update one.+ # 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.+ # Which tool depends on what was asked for, so each subclass names its+ # own.def refusal_for(entry)workflow_key = preferred_workflow_key(entry)diff --git a/spree/core/lib/spree/agent_tools/workflow_tool.rb b/spree/core/lib/spree/agent_tools/workflow_tool.rbindex f72fb35a98..fd1d89f592 100644--- a/spree/core/lib/spree/agent_tools/workflow_tool.rb+++ b/spree/core/lib/spree/agent_tools/workflow_tool.rb@@ -306,8 +306,40 @@ module Spree'The workflow refused the change.'end+ # Who acted, for the workflow keywords that record it.+ #+ # Only where the record can actually hold this principal. Several+ # models still declare `created_by` / `reviewed_by` as a plain+ # `belongs_to` on the admin-user class rather than through `acted_by`,+ # and handing those an API key raises AssociationTypeMismatch deep+ # inside the workflow — a protocol-level failure where the honest+ # outcome is simply an unattributed record.def principal_arguments- schema.principal_parameters.index_with { context.principal }+ principal = context.principal+ schema.principal_parameters.+ select { |name| principal_storable?(name, principal) }.+ index_with { principal }+ end++ # @return [Boolean]+ def principal_storable?(name, principal)+ association = subject_model&.reflect_on_association(name)+ return true if association.nil? || association.polymorphic?++ expected = association.klass+ principal.is_a?(expected)+ rescue NameError+ true+ end++ # The model this workflow writes, for checking what its associations+ # will accept. Nil when the key names nothing resolvable.+ def subject_model+ return @subject_model if defined?(@subject_model)++ @subject_model = created_model+ rescue StandardError+ @subject_model = nilend# Tenancy comes from the credential, never from a parameter.@@ -334,6 +366,11 @@ module Spreereturn { error: "No #{parameter[:model_name].demodulize.underscore.humanize.downcase} found for #{name} #{value.inspect}." } if record.nil?resolved[name] = record+ elsif parameter[:item_type] == 'object'+ rows, refusal = resolve_rows(name, value)+ return refusal if refusal++ resolved[name] = rowselseresolved[name] = valueend@@ -342,6 +379,50 @@ module Spreeresolvedend+ # A list of hashes — a purchase order's or stock transfer's `items:` —+ # names records by prefixed id inside each row, and the workflow builds+ # associations from them. Without resolving those the association is+ # handed a string and the record fails validation with "must exist",+ # which reads to the model as a bad id rather than a missing step.+ #+ # @return [Array(Array<Hash>, nil), Array(nil, Hash)]+ def resolve_rows(name, value)+ rows = Array(value).map do |row|+ next row unless row.is_a?(Hash)++ resolved_row = {}+ row.each do |field, field_value|+ model_name = nested_model_name(field)++ if model_name && field_value.is_a?(String)+ record = find_record(model_name, field_value)+ if record.nil?+ return [nil, { error: "No #{field} found for #{field_value.inspect} in #{name}." }]+ end++ resolved_row[field.to_sym] = record+ else+ resolved_row[field.to_sym] = field_value+ end+ end+ resolved_row+ end++ [rows, nil]+ end++ # Which model a row's field names, taken from the resource map so only+ # something the caller may already read can be referenced.+ #+ # @return [String, nil]+ def nested_model_name(field)+ entry = Spree::AgentTools::ResourceMap.find(field.to_s.pluralize)+ return unless entry+ return unless context.permitted?(entry.permission)++ entry.model_class.name+ end+# Resolves a prefixed id within the caller's store, through the resource# map — so tenancy is answered the same way every read is.#