spree_core 6.0.2 → 6.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. checksums.yaml +4 -4
  2. data/app/jobs/spree/addresses/geocode_address_job.rb +6 -3
  3. data/app/jobs/spree/payments/handle_webhook_job.rb +12 -1
  4. data/app/jobs/spree/variants/remove_line_item_job.rb +5 -0
  5. data/app/models/concerns/spree/has_custom_fields.rb +4 -1
  6. data/app/models/concerns/spree/personal_data_matching.rb +5 -1
  7. data/app/models/concerns/spree/preference_schema.rb +5 -0
  8. data/app/models/concerns/spree/product_scopes.rb +2 -2
  9. data/app/models/concerns/spree/publishable.rb +26 -3
  10. data/app/models/concerns/spree/typed_associations.rb +53 -20
  11. data/app/models/spree/address.rb +2 -2
  12. data/app/models/spree/authentication/strategies/base_strategy.rb +10 -1
  13. data/app/models/spree/cart.rb +7 -2
  14. data/app/models/spree/collection.rb +7 -2
  15. data/app/models/spree/invitation.rb +6 -2
  16. data/app/models/spree/media.rb +25 -1
  17. data/app/models/spree/order.rb +6 -2
  18. data/app/models/spree/price.rb +3 -0
  19. data/app/models/spree/product.rb +21 -14
  20. data/app/models/spree/product_category.rb +7 -1
  21. data/app/models/spree/product_collection.rb +8 -1
  22. data/app/models/spree/promotion.rb +1 -2
  23. data/app/models/spree/seller.rb +93 -10
  24. data/app/models/spree/seller_requirements/complete_profile.rb +26 -7
  25. data/app/models/spree/stock_level.rb +30 -1
  26. data/app/models/spree/stock_movement.rb +1 -0
  27. data/app/services/spree/carts/destroy.rb +22 -6
  28. data/app/services/spree/collections/regenerate_products.rb +37 -15
  29. data/app/services/spree/companies/add_member.rb +9 -4
  30. data/app/services/spree/diagnostics/error_log.rb +139 -0
  31. data/app/services/spree/diagnostics/section.rb +72 -0
  32. data/app/services/spree/diagnostics/sections.rb +121 -0
  33. data/app/services/spree/diagnostics/stack.rb +73 -0
  34. data/app/services/spree/diagnostics.rb +132 -0
  35. data/app/services/spree/newsletter/subscribe.rb +8 -4
  36. data/app/services/spree/orders/create_from_cart.rb +6 -2
  37. data/app/services/spree/orders/remove_line_item.rb +16 -5
  38. data/app/services/spree/product_memberships.rb +21 -1
  39. data/app/services/spree/product_types/apply_to_products.rb +12 -2
  40. data/app/services/spree/products/auto_match_collections.rb +20 -4
  41. data/app/services/spree/stock_reservations/reserve.rb +9 -6
  42. data/app/services/spree/store_credits/apply.rb +9 -1
  43. data/app/services/spree/update_check.rb +7 -31
  44. data/app/tools/spree/agent_tools/create_export.rb +3 -1
  45. data/app/tools/spree/agent_tools/create_import.rb +1 -0
  46. data/app/tools/spree/agent_tools/create_media.rb +2 -1
  47. data/app/tools/spree/agent_tools/create_resource.rb +12 -4
  48. data/app/tools/spree/agent_tools/delete_resource.rb +12 -4
  49. data/app/tools/spree/agent_tools/describe_resource.rb +72 -6
  50. data/app/tools/spree/agent_tools/get_resource.rb +8 -5
  51. data/app/tools/spree/agent_tools/resource_write.rb +16 -3
  52. data/app/tools/spree/agent_tools/search_resources.rb +51 -20
  53. data/app/tools/spree/agent_tools/update_resource.rb +6 -6
  54. data/app/tools/spree/agent_tools/upload_file.rb +1 -0
  55. data/app/workflows/spree/carts/add_item.rb +51 -0
  56. data/app/workflows/spree/carts/complete.rb +18 -3
  57. data/app/workflows/spree/carts/merge.rb +25 -4
  58. data/app/workflows/spree/orders/complete.rb +39 -14
  59. data/app/workflows/spree/payments/handle_webhook.rb +7 -3
  60. data/app/workflows/spree/products/activate.rb +7 -2
  61. data/app/workflows/spree/products/archive.rb +7 -2
  62. data/app/workflows/spree/products/draft.rb +7 -2
  63. data/app/workflows/spree/products/status_transition.rb +24 -0
  64. data/app/workflows/spree/sellers/approve.rb +6 -0
  65. data/app/workflows/spree/sellers/create.rb +5 -2
  66. data/app/workflows/spree/stock_levels/bulk_upsert.rb +19 -7
  67. data/config/locales/be.yml +1 -1
  68. data/config/locales/en.yml +11 -0
  69. data/config/locales/fr.yml +1 -1
  70. data/config/locales/lt.yml +1 -1
  71. data/config/locales/ru.yml +1 -1
  72. data/config/locales/uk.yml +1 -1
  73. data/db/migrate/20240303174340_fix_spree_stock_item_unique_index.rb +14 -10
  74. data/db/migrate/20260814000001_rename_stock_items_to_stock_levels.rb +13 -7
  75. data/lib/generators/spree/api_resource/api_resource_generator.rb +35 -3
  76. data/lib/generators/spree/api_resource/templates/admin_controller.rb.tt +9 -4
  77. data/lib/generators/spree/api_resource/templates/admin_integration_spec.rb.tt +74 -0
  78. data/lib/generators/spree/api_resource/templates/store_controller.rb.tt +11 -6
  79. data/lib/spree/agent_tool.rb +105 -1
  80. data/lib/spree/agent_tools/default_catalog.rb +16 -21
  81. data/lib/spree/agent_tools/legacy_tools.rb +212 -0
  82. data/lib/spree/agent_tools/operation_catalog.rb +206 -0
  83. data/lib/spree/agent_tools/operation_tool.rb +189 -0
  84. data/lib/spree/agent_tools/record_summary.rb +8 -2
  85. data/lib/spree/agent_tools/registry.rb +65 -31
  86. data/lib/spree/agent_tools/resource_map.rb +207 -9
  87. data/lib/spree/agent_tools.rb +3 -3
  88. data/lib/spree/core/dependencies_helper.rb +96 -40
  89. data/lib/spree/core/engine.rb +12 -1
  90. data/lib/spree/core/version.rb +1 -1
  91. data/lib/spree/core.rb +30 -2
  92. data/lib/spree/reporting/default_vocabulary.rb +25 -5
  93. data/lib/spree/testing_support/extension_rake.rb +12 -0
  94. data/lib/spree/upgrades/5_6_to_6_0/manifest.yml +34 -0
  95. data/lib/tasks/dependencies.rake +2 -2
  96. data/lib/tasks/diagnostics.rake +11 -0
  97. metadata +29 -7
  98. data/lib/spree/agent_tools/workflow_endpoints.rb +0 -88
  99. data/lib/spree/agent_tools/workflow_schema.rb +0 -279
  100. data/lib/spree/agent_tools/workflow_tool.rb +0 -654
@@ -0,0 +1,206 @@
1
+ module Spree
2
+ module AgentTools
3
+ # Every Admin API operation an agent may call by name, and what it takes.
4
+ #
5
+ # A contract like {ResourceMap}: core declares the shape, and `spree_api`
6
+ # fills it from the Admin API's OpenAPI document — core's and every
7
+ # extension's — and the routes behind it. An operation that gains an
8
+ # endpoint is a tool in the same commit, with the summary, description and
9
+ # request body its rswag spec wrote.
10
+ #
11
+ # See docs/plans/6.0-agent-tools-from-openapi.md.
12
+ module OperationCatalog
13
+ # @!attribute name
14
+ # @return [String] the tool name, `orders_cancel`
15
+ # @!attribute verb
16
+ # @return [String] 'post', 'patch', 'put', 'delete' or 'get'
17
+ # @!attribute path
18
+ # @return [String] the OpenAPI path, with `{name}` segments
19
+ # @!attribute description
20
+ # @return [String] what the model reads when choosing the tool
21
+ # @!attribute summary
22
+ # @return [String] the operation summary, for the confirmation line
23
+ # @!attribute permission
24
+ # @return [String] the scope gating it, from the routed controller
25
+ # @!attribute resource_key
26
+ # @return [String, nil] the resource-map key of the routed controller's
27
+ # model, so a parent segment can be read off the record
28
+ # @!attribute path_params
29
+ # @return [Array<String>] the dynamic segments, in path order
30
+ # @!attribute body_properties
31
+ # @return [Hash{String => Hash}] the request body's JSON Schema
32
+ # properties, references inlined
33
+ # @!attribute body_required
34
+ # @return [Array<String>]
35
+ # @!attribute path_descriptions
36
+ # @return [Hash{String => String}]
37
+ # @!attribute listed
38
+ # @return [Boolean] false for a 6.0.0 name kept callable through 6.0.x
39
+ # @!attribute legacy_parameters
40
+ # @return [Hash{String => String, nil}] 6.0.0 parameter => its name now
41
+ Entry = Struct.new(:name, :verb, :path, :description, :summary, :permission, :resource_key,
42
+ :path_params, :body_properties, :body_required, :path_descriptions,
43
+ :listed, :legacy_parameters, keyword_init: true) do
44
+ # @return [Boolean] a read opted in to the catalog
45
+ def read?
46
+ verb == 'get'
47
+ end
48
+
49
+ # @return [Boolean] whether the call changes the store
50
+ def mutating
51
+ !read?
52
+ end
53
+
54
+ # The resource each `{x_id}` segment names, read off the path itself —
55
+ # `/orders/{order_id}/items` names `orders` — so a renamed nested
56
+ # route still points at the right resource.
57
+ #
58
+ # @return [Hash{String => String}] segment => resource key
59
+ def segment_keys
60
+ path.scan(%r{/([a-z_]+)/\{([a-z_]+_id)\}}).to_h { |key, segment| [segment, key] }
61
+ end
62
+
63
+ # The segments a call may leave out, read off the record a later
64
+ # segment names. The innermost is the record the call is about, never
65
+ # one to read off another.
66
+ #
67
+ # @return [Hash{String => String}] segment => resource key
68
+ def parent_keys
69
+ segment_keys.except(path_params.last)
70
+ end
71
+
72
+ # @param values [Hash{String => String}] path segment => value
73
+ # @return [String, nil] nil while a segment is unfilled
74
+ def path_for(values)
75
+ filled = path.gsub(/\{([a-z_]+)\}/) do
76
+ value = values[Regexp.last_match(1)]
77
+ value.present? ? ERB::Util.url_encode(value.to_s) : Regexp.last_match(0)
78
+ end
79
+ filled unless filled.include?('{')
80
+ end
81
+
82
+ # The tool's arguments as JSON Schema: the path segments and the
83
+ # request body, side by side.
84
+ #
85
+ # A segment or field a 6.0.0 name still reaches is left out of
86
+ # `required` through 6.0.x — a client validating against the schema
87
+ # would otherwise refuse the old name before the tool could map it —
88
+ # and so is a parent segment, which the tool can read off the record
89
+ # the call names. The tool checks both itself.
90
+ #
91
+ # @return [Hash]
92
+ def input_schema
93
+ properties = path_params.to_h do |segment|
94
+ [segment, { 'type' => 'string', 'description' => path_descriptions[segment] }.compact]
95
+ end.merge(body_properties)
96
+
97
+ aliased = legacy_parameters.values.grep(String)
98
+ parents = parent_keys.keys
99
+ # A 6.0.0 name no longer listed keeps the 6.0.0 contract, which
100
+ # required nothing the operation's body now does.
101
+ required = listed ? (path_params + body_required).uniq - aliased - parents : []
102
+
103
+ { 'type' => 'object', 'properties' => properties, 'required' => required }
104
+ end
105
+ end
106
+
107
+ class << self
108
+ # How the catalog fills itself the first time it is read. `spree_api`
109
+ # sets it to its walk over the document; an installation without the
110
+ # API engine has no operations to offer.
111
+ #
112
+ # @return [#call, nil]
113
+ attr_accessor :deriver
114
+
115
+ # @return [Array<Entry>] the operations offered by name
116
+ def all
117
+ derive!
118
+ entries.values
119
+ end
120
+
121
+ # The 6.0.0 names kept callable through 6.0.x, which no listing shows.
122
+ #
123
+ # @return [Array<Entry>]
124
+ def aliases
125
+ derive!
126
+ alias_entries.values
127
+ end
128
+
129
+ # A tool by its name, including a 6.0.0 name no longer listed.
130
+ #
131
+ # @param name [String]
132
+ # @return [Entry, nil]
133
+ def find(name)
134
+ derive!
135
+ entries[name.to_s] || alias_entries[name.to_s]
136
+ end
137
+
138
+ # Registers one operation. Re-registering a name replaces it, because
139
+ # the walk runs again after a code reload.
140
+ #
141
+ # @return [Entry]
142
+ def register(**attributes)
143
+ entry = build(listed: true, **attributes)
144
+ entries[entry.name] = entry
145
+ end
146
+
147
+ # Registers a 6.0.0 name for an operation, callable but not listed.
148
+ # A name an offered operation already has keeps that operation.
149
+ #
150
+ # @return [Entry, nil]
151
+ def register_alias(**attributes)
152
+ entry = build(**attributes, listed: false)
153
+ alias_entries[entry.name] = entry unless entries.key?(entry.name)
154
+ end
155
+
156
+ # @return [void]
157
+ def reset!
158
+ @entries = {}
159
+ @alias_entries = {}
160
+ end
161
+
162
+ # Marks the catalog for rebuilding on its next read.
163
+ #
164
+ # @return [void]
165
+ def stale!
166
+ @derived = false
167
+ end
168
+
169
+ # Fills the catalog once, under a mutex. The flag is set only once the
170
+ # deriver has finished, so a second reader waits on the mutex instead
171
+ # of reading a catalog the deriver has just emptied. Nothing the
172
+ # deriver calls reads the catalog back, so it cannot recurse.
173
+ #
174
+ # @return [void]
175
+ def derive!
176
+ return if @derived || deriver.nil?
177
+
178
+ derive_mutex.synchronize do
179
+ next if @derived
180
+
181
+ deriver.call
182
+ @derived = true
183
+ end
184
+ end
185
+
186
+ private
187
+
188
+ def build(**attributes)
189
+ Entry.new(legacy_parameters: {}, body_properties: {}, body_required: [], path_descriptions: {}, **attributes)
190
+ end
191
+
192
+ def entries
193
+ @entries ||= {}
194
+ end
195
+
196
+ def alias_entries
197
+ @alias_entries ||= {}
198
+ end
199
+
200
+ def derive_mutex
201
+ @derive_mutex ||= Mutex.new
202
+ end
203
+ end
204
+ end
205
+ end
206
+ end
@@ -0,0 +1,189 @@
1
+ module Spree
2
+ module AgentTools
3
+ # One agent tool per Admin API operation in {OperationCatalog}.
4
+ #
5
+ # Everything about the tool is the operation's: its name, its prose, its
6
+ # arguments and the request it sends. The arguments are the path segments
7
+ # and the request body under the names the document gives them, so a call
8
+ # is a request with no translation step between what the model was shown
9
+ # and what the endpoint receives. The endpoint runs its own routing,
10
+ # authentication, scope check, record-level ability and workflow.
11
+ #
12
+ # Generated classes are cached per entry, so a catalog rebuilt after a
13
+ # code reload produces new tools rather than serving stale ones.
14
+ #
15
+ # See docs/plans/6.0-agent-tools-from-openapi.md.
16
+ class OperationTool < Spree::AgentTool
17
+ class_attribute :operation, instance_accessor: false
18
+
19
+ class << self
20
+ # @param entry [OperationCatalog::Entry]
21
+ # @return [Class<OperationTool>]
22
+ def for(entry)
23
+ # By identity: an entry is rebuilt, as a new object, whenever the
24
+ # catalog is, and hashing one walks its whole request schema.
25
+ cache[entry] ||= Class.new(self) do
26
+ self.operation = entry
27
+
28
+ tool_name entry.name
29
+ description entry.description
30
+ permission entry.permission
31
+ mutating! if entry.mutating
32
+ end
33
+ end
34
+
35
+ # @return [Hash] JSON Schema for the arguments, read by the adapters
36
+ def input_schema
37
+ @input_schema ||= operation.input_schema
38
+ end
39
+
40
+ # @return [void]
41
+ def clear_cache!
42
+ @cache = {}
43
+ end
44
+
45
+ private
46
+
47
+ def cache
48
+ @cache ||= {}.compare_by_identity
49
+ end
50
+ end
51
+
52
+ delegate :operation, to: :class
53
+
54
+ # @return [Hash] the result handed back to the model
55
+ def call(**arguments)
56
+ arguments, notes = map_legacy_arguments(arguments.transform_keys(&:to_s))
57
+
58
+ segments = operation.path_params.index_with { |segment| arguments[segment] }
59
+ derive_parents(segments)
60
+ path = operation.path_for(segments)
61
+ # Only what the path needs is checked here. What the body requires is
62
+ # the endpoint's to refuse, in its own words.
63
+ if path.nil?
64
+ unfilled = segments.select { |_segment, value| value.blank? }.keys
65
+ return { error: "#{tool_name} needs #{unfilled.to_sentence}.", deprecations: notes.presence }.compact
66
+ end
67
+
68
+ values, refusal = body_for(arguments)
69
+ return refusal.merge(deprecations: notes.presence).compact if refusal
70
+
71
+ response = dispatch(path, values)
72
+ return { error: response.error_message, deprecations: notes.presence }.compact unless response.success?
73
+
74
+ # A read opted in to the catalog answers with what it read, filtered
75
+ # like every other record that leaves for a model.
76
+ return { summary: operation.summary, data: sanitized(response.data) } if operation.read?
77
+
78
+ record = payload_summary(response.data)
79
+ named = record&.dig(:title).presence || record&.dig(:id).presence || record&.dig('id').presence
80
+ { summary: named ? "#{operation.summary} #{named}" : summary(arguments), record: record,
81
+ deprecations: notes.presence }.compact
82
+ end
83
+
84
+ # The line a client shows before the call runs: the operation's own
85
+ # summary and the records it names.
86
+ #
87
+ # @param arguments [Hash]
88
+ # @return [String]
89
+ def summary(arguments)
90
+ arguments, = map_legacy_arguments(arguments.transform_keys(&:to_s))
91
+ named = operation.path_params.filter_map { |segment| arguments[segment] }
92
+ [operation.summary, named.reverse.join(' ').presence].compact.join(' ')
93
+ end
94
+
95
+ private
96
+
97
+ # 6.0.0 names (`order`, `reason`) mapped to the operation's (`id`,
98
+ # `cancel_reason_id`), with a note per name so the model learns the new
99
+ # one. A name the endpoint never read is dropped and said to be.
100
+ def map_legacy_arguments(arguments)
101
+ renames = operation.legacy_parameters
102
+ return [arguments, []] if renames.blank?
103
+
104
+ notes = []
105
+ mapped = arguments.each_with_object({}) do |(name, value), result|
106
+ next result[name] = value unless renames.key?(name)
107
+
108
+ target = renames[name]
109
+ if target == :merge && value.is_a?(Hash)
110
+ notes << "#{name} is deprecated: send its fields as arguments of their own."
111
+ result.merge!(value.transform_keys(&:to_s)) { |_key, given, _merged| given }
112
+ elsif target.nil? || target == :merge
113
+ notes << "#{name} is not something #{tool_name} sets, and was ignored."
114
+ else
115
+ notes << "#{name} is deprecated: use #{target}."
116
+ result[target] = value unless result.key?(target)
117
+ end
118
+ end
119
+
120
+ [mapped, notes]
121
+ end
122
+
123
+ # A parent segment the caller left out, read off a record the call
124
+ # does name — a payment's order, a fulfillment's order — through the
125
+ # resource map, under the caller's store. Only a record the caller may
126
+ # read is consulted; anything else stays unfilled and is asked for.
127
+ def derive_parents(segments)
128
+ missing = operation.parent_keys.keys.select { |segment| segments[segment].blank? }
129
+ return if missing.empty?
130
+
131
+ records = segments.compact_blank.to_a.reverse.filter_map { |segment, id| record_for(segment, id) }
132
+ missing.reverse_each do |segment|
133
+ parent = records.lazy.filter_map { |record| record.try(segment.delete_suffix('_id')) }.first
134
+ next if parent.nil?
135
+
136
+ segments[segment] = parent.try(:prefixed_id)
137
+ records << parent
138
+ end
139
+ end
140
+
141
+ def record_for(segment, id)
142
+ key = segment == 'id' ? operation.resource_key : operation.segment_keys[segment]
143
+ entry = key && ResourceMap.find(key)
144
+ return if entry.nil? || !entry.readable_by?(context)
145
+
146
+ entry.scope_for(context).find_by_prefix_id(id)
147
+ rescue StandardError
148
+ nil
149
+ end
150
+
151
+ def dispatch(path, values)
152
+ dispatcher = ApiDispatch.new(context)
153
+ return dispatcher.call(method: :get, path: path, params: values || {}) if operation.read?
154
+
155
+ dispatcher.call(method: operation.verb.to_sym, path: path, body: values)
156
+ end
157
+
158
+ # What travels as the body, or a read's query: every argument that is
159
+ # not a path segment, checked against the document so a guessed field is
160
+ # named back rather than dropped behind a success.
161
+ def body_for(arguments)
162
+ body = arguments.except(*operation.path_params)
163
+ return [nil, nil] if body.empty?
164
+
165
+ accepted = operation.body_properties.keys
166
+ unknown = body.keys - accepted
167
+ return [body, nil] if unknown.empty?
168
+
169
+ [nil, { error: "#{tool_name} does not accept #{unknown.to_sentence}.",
170
+ accepted_arguments: (operation.path_params + accepted).sort }]
171
+ end
172
+
173
+ # The record the endpoint returned, compacted and filtered the way a
174
+ # record read from the map is.
175
+ def payload_summary(data)
176
+ return unless data.is_a?(Hash)
177
+
178
+ entry = operation.resource_key && ResourceMap.find(operation.resource_key)
179
+ return sanitized(data).slice('id').presence if entry.nil?
180
+
181
+ RecordSummary.from_payload(entry: entry, payload: data)
182
+ end
183
+
184
+ def sanitized(data)
185
+ RecordSummary.sanitize(data, operation.resource_key)
186
+ end
187
+ end
188
+ end
189
+ end
@@ -9,7 +9,12 @@ module Spree
9
9
  # Fields worth showing beneath the title, in the order they are preferred.
10
10
  # Status is deliberately absent — it has its own badge on the row, and
11
11
  # repeating it would push out the field that actually adds something.
12
- SUBTITLE_FIELDS = %w[display_total display_price price email number sku].freeze
12
+ SUBTITLE_FIELDS = %w[display_total display_price price email number sku variant_sku].freeze
13
+
14
+ # Quantities and places a list row must carry for the model to answer
15
+ # from the search alone. Without them a stock level row was an id and
16
+ # nothing else, and "how much do I have" took one lookup per row.
17
+ DETAIL_FIELDS = %w[count_on_hand available_count stock_location_name options_text].freeze
13
18
 
14
19
  # Anything that looks like a credential is dropped before a record can
15
20
  # reach the model. The serializers are supposed to mask these already —
@@ -151,6 +156,7 @@ module Spree
151
156
  title: title,
152
157
  subtitle: subtitle_for(attributes, title),
153
158
  status: attributes['status'],
159
+ details: attributes.slice(*DETAIL_FIELDS).compact.presence,
154
160
  image_url: attributes['thumbnail_url'],
155
161
  path: dashboard_path_from(entry, attributes['id'])
156
162
  }.compact
@@ -160,7 +166,7 @@ module Spree
160
166
 
161
167
  # The same preference order as a record's title, read from the payload.
162
168
  def title_from(attributes)
163
- %w[name number label title email sku].each do |field|
169
+ %w[name number label title email sku variant_name].each do |field|
164
170
  value = attributes[field]
165
171
  return value.to_s if value.is_a?(String) && value.present?
166
172
  end
@@ -18,10 +18,9 @@ module Spree
18
18
  # of their own — they are gated per resource instead — so the registry
19
19
  # cannot be the only thing keeping them apart.
20
20
  #
21
- # Writes are not registered as classes. A back-office write already is a
22
- # workflow, so the registry exposes workflows by their `Spree::Dependencies`
23
- # key and derives each tool from the workflow's own `perform` signature —
24
- # see {#expose_workflows}.
21
+ # Writes are not registered as classes. Every Admin API action an admin
22
+ # key may call is already a tool, built from its OpenAPI operation by
23
+ # {OperationCatalog} — see docs/plans/6.0-agent-tools-from-openapi.md.
25
24
  class Registry
26
25
  include Enumerable
27
26
 
@@ -61,38 +60,54 @@ module Spree
61
60
  to_a.each(&)
62
61
  end
63
62
 
64
- # Exposes workflows as write tools, keyed by `Spree::Dependencies` key so
65
- # the tool follows whatever class the host app has registered:
66
- #
67
- # Spree.admin_agent_tools.expose_workflows(
68
- # order_cancel_workflow: 'write_orders',
69
- # product_activate_workflow: 'write_products'
70
- # )
71
- #
72
- # A value may be the permission key on its own, or a hash carrying it
73
- # alongside `except:` (parameters to hide, such as a deprecated one) and
74
- # `summary:` (a callable overriding the generated confirmation line).
63
+ # @deprecated Admin API operations are agent tools on their own, built
64
+ # from the OpenAPI document, so there is nothing to expose. A
65
+ # workflow behind a documented endpoint is that endpoint's tool; one
66
+ # without is not offered. Recorded and otherwise ignored, and removed
67
+ # in 7.0.
75
68
  #
76
69
  # @param exposures [Hash{Symbol => String, Hash}]
77
70
  # @return [self]
78
71
  def expose_workflows(**exposures)
79
- exposures.each do |dependency_key, options|
80
- options = { permission: options } if options.is_a?(String) || options.is_a?(Symbol)
81
- @exposed_workflows[dependency_key.to_sym] = {
82
- permission: options.fetch(:permission).to_s,
83
- except: Array(options[:except]).map(&:to_sym),
84
- summary: options[:summary]
85
- }
86
- end
72
+ Spree::Deprecation.warn(
73
+ 'Spree.admin_agent_tools.expose_workflows is deprecated and has no effect: every documented ' \
74
+ 'Admin API action is an agent tool, built from its OpenAPI operation. A workflow reaches agents ' \
75
+ 'through an admin endpoint whose rswag spec is generated into the openapi/admin.yaml your gem ships. ' \
76
+ 'See docs/plans/6.0-agent-tools-from-openapi.md.'
77
+ )
78
+
79
+ @exposed_workflows.merge!(exposures.transform_keys(&:to_sym))
87
80
  self
88
81
  end
89
82
 
90
- # @return [Hash{Symbol => Hash}] every exposed workflow, by dependency key
83
+ # @deprecated see {#expose_workflows}
84
+ # @return [Hash{Symbol => Hash}] what was passed to {#expose_workflows}
91
85
  attr_reader :exposed_workflows
92
86
 
93
87
  # @return [Array<Class<Spree::AgentTool>>]
94
88
  def to_a
95
- registered_classes + workflow_tool_classes
89
+ registered = registered_classes
90
+ registered + operation_tool_classes(registered.map(&:tool_name))
91
+ end
92
+
93
+ # A tool this caller may use, by name — including a 6.0.0 name that is
94
+ # no longer listed but still answers through 6.0.x, so a client that
95
+ # learned it keeps working.
96
+ #
97
+ # @param name [String]
98
+ # @param context [Spree::AgentTools::Context]
99
+ # @return [Spree::AgentTool, nil]
100
+ def find_for(name, context)
101
+ name = name.to_s
102
+ tool_class = registered_classes.find { |klass| klass.tool_name == name }
103
+ if tool_class.nil? && operations?
104
+ entry = Spree::AgentTools::OperationCatalog.find(name)
105
+ tool_class = entry && Spree::AgentTools::OperationTool.for(entry)
106
+ end
107
+ return if tool_class.nil? || (tool_class.try(:audience) && tool_class.audience != audience)
108
+
109
+ tool = tool_class.new(context)
110
+ tool if tool.permitted?
96
111
  end
97
112
 
98
113
  # Tools this caller may actually use, instantiated for their context.
@@ -118,14 +133,33 @@ module Spree
118
133
  end
119
134
  end
120
135
 
121
- # One generated tool class per exposed workflow whose dependency key
122
- # still resolves. A key an extension removed simply stops being offered
123
- # rather than breaking the whole catalog.
124
- def workflow_tool_classes
125
- @exposed_workflows.filter_map do |dependency_key, options|
126
- Spree::AgentTools::WorkflowTool.for(dependency_key, **options)
136
+ # One tool per operation the catalog lists. Operations are back-office
137
+ # actions, so only the admin surface offers them.
138
+ #
139
+ # A registered tool keeps its name: an operation claiming the same one
140
+ # would make an MCP server refuse the whole list. The contract spec
141
+ # fails on such a clash; at runtime it is logged, once per name.
142
+ def operation_tool_classes(taken)
143
+ return [] unless operations?
144
+
145
+ Spree::AgentTools::OperationCatalog.all.filter_map do |entry|
146
+ next Spree::AgentTools::OperationTool.for(entry) unless taken.include?(entry.name)
147
+
148
+ warn_shadowed(entry.name)
149
+ nil
127
150
  end
128
151
  end
152
+
153
+ def warn_shadowed(name)
154
+ @shadowed ||= Set.new
155
+ return unless @shadowed.add?(name)
156
+
157
+ Rails.logger.warn("[Spree] agent tool #{name} is registered by hand; the operation of that name is not offered")
158
+ end
159
+
160
+ def operations?
161
+ audience == :admin
162
+ end
129
163
  end
130
164
  end
131
165
  end