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
@@ -16,10 +16,36 @@ module Spree
16
16
  # than quietly leaking another store's records.
17
17
  UnscopedResourceError = Class.new(StandardError)
18
18
 
19
+ # The parent segment of a nested path: `/promotions/:promotion_id/promotion_rules`
20
+ # names `promotions`.
21
+ PARENT_SEGMENT = %r{/(?<parent>[a-z_]+)/:[a-z_]+_id(?:/|\z)}
22
+
19
23
  Entry = Struct.new(:key, :model_name, :permission, :serializer_name,
20
24
  :dashboard_path, :scope_name, :write_permission,
21
25
  :writable_attributes, :create_workflow_key, :update_workflow_key,
22
- :distinct, :api_paths, keyword_init: true) do
26
+ :distinct, :api_paths, :index_paths, :access_permissions, keyword_init: true) do
27
+ # Whether this caller may read the resource.
28
+ #
29
+ # Imports and exports have no key of their own: each record is gated
30
+ # by the scope of the resource it carries. They list those keys in
31
+ # `access_permissions`, and holding any one of them is enough to
32
+ # reach the endpoint, which filters to the records that key covers.
33
+ #
34
+ # @param context [Spree::AgentTools::Context]
35
+ # @return [Boolean]
36
+ def readable_by?(context)
37
+ return context.permitted?(permission) if access_permissions.nil?
38
+
39
+ access_permissions.any? { |key| context.holds?(key) }
40
+ end
41
+
42
+ # Every key that can open this resource.
43
+ #
44
+ # @return [Array<String>]
45
+ def permission_keys
46
+ access_permissions || [permission]
47
+ end
48
+
23
49
  # The Admin API path for one of this resource's operations, which is
24
50
  # how a tool reaches it.
25
51
  #
@@ -29,9 +55,38 @@ module Spree
29
55
  Array(api_paths).to_h[action.to_sym]
30
56
  end
31
57
 
32
- # @return [Boolean] whether a tool can dispatch to this resource
58
+ # Whether a tool can dispatch to this resource's collection on its own.
59
+ #
60
+ # A resource reached only under a parent is not: the tool has no
61
+ # parent id to put in the path, and dispatching the template as it
62
+ # stands answered "Promotion not found" for a search of promotion
63
+ # rules, which a model repeats as a fact about the store.
64
+ #
65
+ # @return [Boolean]
33
66
  def dispatchable?
34
- api_path(:index).present?
67
+ api_path(:index).present? && !nested?(:index)
68
+ end
69
+
70
+ # Whether the path a tool would dispatch `action` to runs under a
71
+ # parent. Asked per action, because a resource can be listed at the
72
+ # top level and written under its parent (`/variants`,
73
+ # `/products/:product_id/variants`).
74
+ #
75
+ # @param action [Symbol]
76
+ # @return [Boolean]
77
+ def nested?(action = :index)
78
+ parent_key(action).present?
79
+ end
80
+
81
+ # The resource key of the parent `action`'s path runs under, read
82
+ # from the route rather than guessed from the model, so a renamed
83
+ # nested route (`/orders/:order_id/items`) still names `orders`. The
84
+ # innermost parent, for a path nested twice.
85
+ #
86
+ # @param action [Symbol]
87
+ # @return [String, nil]
88
+ def parent_key(action = :index)
89
+ api_path(action).to_s.scan(PARENT_SEGMENT).flatten.last
35
90
  end
36
91
 
37
92
  # Whether a search may add DISTINCT.
@@ -67,6 +122,62 @@ module Spree
67
122
  Array(writable_attributes).map(&:to_s).sort
68
123
  end
69
124
 
125
+ # The record a nested resource is reached through — `order_id` for an
126
+ # order's items, discounts and fees — or nil for a top-level one.
127
+ #
128
+ # @param action [Symbol]
129
+ # @return [String, nil]
130
+ def parent_param(action)
131
+ param_in(api_path(action))
132
+ end
133
+
134
+ # The records this resource can be listed under, each with the
135
+ # collection path that lists it there — claims under an order,
136
+ # products under a category or collection, variants under a product.
137
+ # A path nested twice is left out: one parent id cannot fill it.
138
+ #
139
+ # @return [Hash{String => String}] parent resource key => path
140
+ def index_parents
141
+ Array(index_paths.presence || api_path(:index)).each_with_object({}) do |path, parents|
142
+ next unless path.scan(/:[a-z_]+_id\b/).one?
143
+
144
+ parent = path.scan(PARENT_SEGMENT).flatten.first
145
+ parents[parent] ||= path if parent
146
+ end
147
+ end
148
+
149
+ # The operation's path with its segments filled, or nil when a nested
150
+ # resource was not given the record it lives under.
151
+ #
152
+ # A search given a parent runs on the collection under that parent,
153
+ # chosen by the parent id's prefix, and is nil when the resource is
154
+ # not listed under that kind of record. Listing the whole store
155
+ # instead answered "the claims on order B" with every claim.
156
+ #
157
+ # Each value is percent-encoded so it stays one segment: a `?` or `/`
158
+ # in an id would otherwise send the call to a different route than
159
+ # the one the tool checked and the approver was shown. A path with a
160
+ # segment left unfilled — a resource nested two levels deep — is nil
161
+ # too, rather than dispatched with a placeholder in it.
162
+ #
163
+ # @param action [Symbol]
164
+ # @param id [String, nil]
165
+ # @param parent_id [String, nil]
166
+ # @return [String, nil]
167
+ def path_for(action, id: nil, parent_id: nil)
168
+ path = action.to_sym == :index && parent_id.present? ? index_path_under(parent_id) : api_path(action)
169
+ return if path.blank?
170
+
171
+ path = path.sub(':id', ERB::Util.url_encode(id.to_s)) if id.present?
172
+ parent = param_in(path)
173
+ if parent
174
+ return if parent_id.blank?
175
+
176
+ path = path.sub(":#{parent}", ERB::Util.url_encode(parent_id.to_s))
177
+ end
178
+ path unless path.match?(/:[a-z_]+/)
179
+ end
180
+
70
181
  # The associations the show operation will include when asked, read
71
182
  # from the serializer that renders it.
72
183
  #
@@ -92,14 +203,68 @@ module Spree
92
203
  end
93
204
 
94
205
  def expand_names_in(klass)
95
- file = Object.const_source_location(klass.name)&.first
96
- return [] if file.nil? || !File.exist?(file)
206
+ file = serializer_file(klass)
207
+ return [] if file.nil?
97
208
 
98
- File.read(file).scan(/expand\?\('([a-z_]+)'\)/).flatten
209
+ # Comment lines are skipped: the base serializer explains `expand?`
210
+ # with an example, which put `variants` on every resource's list.
211
+ code = File.readlines(file).reject { |line| line.lstrip.start_with?('#') }.join
212
+ code.scan(/expand\?\('([a-z_]+)'\)/).flatten
99
213
  rescue StandardError
100
214
  []
101
215
  end
102
216
 
217
+ # The file the autoloader maps the class to, under whichever engine
218
+ # holds it. `const_source_location` is the fallback: it names the file
219
+ # that first touched the constant, which for a serializer another one
220
+ # inherits from was the subclass's file.
221
+ def serializer_file(klass)
222
+ relative = "#{klass.name.underscore}.rb"
223
+ found = Rails.autoloaders.main.dirs.lazy.map { |dir| File.join(dir, relative) }.find { |path| File.exist?(path) }
224
+ found || Object.const_source_location(klass.name)&.first.then { |path| path if path && File.exist?(path) }
225
+ end
226
+
227
+ # The STI family this resource is, when its rows are selected by a
228
+ # `type` the model's own registry resolves — payment methods, seller
229
+ # requirements, promotion rules. Nil for an ordinary resource.
230
+ #
231
+ # @return [Class, nil]
232
+ def typed_family
233
+ typed_family_class(model_class)
234
+ end
235
+
236
+ # The STI family behind each list-valued attribute whose rows carry a
237
+ # `type` — a promotion's `rules` and `actions`, a price list's
238
+ # `rules`. The attribute is the short name the write accepts; the
239
+ # association behind it carries the model's prefix
240
+ # (`promotion_rules`), which is how the two are matched.
241
+ #
242
+ # @return [Hash{String => Class}] attribute => family class
243
+ def nested_typed_families
244
+ nested_collection_shapes.each_with_object({}) do |(name, fields), families|
245
+ next unless fields.any? { |field| field['name'] == 'type' }
246
+
247
+ family = typed_family_class(typed_association_for(name)&.klass)
248
+ families[name] = family if family
249
+ end
250
+ rescue StandardError
251
+ {}
252
+ end
253
+
254
+ def typed_association_for(name)
255
+ reflections = model_class.reflect_on_all_associations(:has_many)
256
+ reflections.find { |reflection| reflection.name.to_s == name } ||
257
+ reflections.find { |reflection| reflection.name.to_s.end_with?("_#{name}") }
258
+ end
259
+
260
+ def typed_family_class(klass)
261
+ return unless klass.respond_to?(:subclass_registry) && klass.subclass_registry
262
+
263
+ klass
264
+ rescue StandardError
265
+ nil
266
+ end
267
+
103
268
  # The shape of each attribute that carries a list of records — a
104
269
  # product's `variants`, an order's `items`.
105
270
  #
@@ -152,6 +317,15 @@ module Spree
152
317
  model_name.constantize
153
318
  end
154
319
 
320
+ # The prefix of this resource's ids (`or` for orders), or nil.
321
+ #
322
+ # @return [String, nil]
323
+ def id_prefix
324
+ model_class.try(:_prefix_id_prefix).presence
325
+ rescue NameError
326
+ nil
327
+ end
328
+
155
329
  # Records of this kind the asking admin may see.
156
330
  #
157
331
  # Takes the context rather than the store so the ability filter cannot
@@ -219,6 +393,23 @@ module Spree
219
393
  def filterable_scopes
220
394
  model_class.ransackable_scopes.map(&:to_s).sort
221
395
  end
396
+
397
+ private
398
+
399
+ def param_in(path)
400
+ Array(path&.scan(/:([a-z_]+)/)).flatten.reject { |name| name == 'id' }.first
401
+ end
402
+
403
+ # One parent needs no matching; the endpoint answers for an id of the
404
+ # wrong kind. Several are told apart by the id's prefix (`ctg_` is a
405
+ # category, `coll_` a collection).
406
+ def index_path_under(parent_id)
407
+ parents = index_parents
408
+ return parents.values.first if parents.one?
409
+
410
+ prefix = parent_id.to_s[/\A([a-z]+)_/, 1]
411
+ parents.find { |key, _path| prefix && ResourceMap.find(key)&.id_prefix == prefix }&.last
412
+ end
222
413
  end
223
414
 
224
415
 
@@ -258,10 +449,15 @@ module Spree
258
449
  # @param distinct [Boolean, nil] false where the controller disables
259
450
  # DISTINCT on its own collection, which Postgres requires when the
260
451
  # sort column is not in the select list
452
+ # @param index_paths [Array<String>, nil] every collection path the
453
+ # resource is listed at, the nested ones under a parent included
454
+ # @param access_permissions [Array<String>, nil] keys any one of which
455
+ # opens the resource, in place of `permission`
261
456
  # @return [Entry]
262
457
  def register(key:, model_name:, permission:, serializer_name:, dashboard_path: nil, scope_name: nil,
263
458
  write_permission: nil, writable_attributes: [], create_workflow_key: nil,
264
- update_workflow_key: nil, distinct: nil, api_paths: nil)
459
+ update_workflow_key: nil, distinct: nil, api_paths: nil, index_paths: nil,
460
+ access_permissions: nil)
265
461
  entry = Entry.new(key: key.to_s, model_name: model_name, permission: permission,
266
462
  serializer_name: serializer_name, dashboard_path: dashboard_path,
267
463
  scope_name: scope_name, write_permission: write_permission,
@@ -269,7 +465,9 @@ module Spree
269
465
  create_workflow_key: create_workflow_key,
270
466
  update_workflow_key: update_workflow_key,
271
467
  distinct: distinct,
272
- api_paths: api_paths&.to_a)
468
+ api_paths: api_paths&.to_a,
469
+ index_paths: index_paths,
470
+ access_permissions: access_permissions)
273
471
  entries[entry.key] = entry
274
472
  end
275
473
 
@@ -334,7 +532,7 @@ module Spree
334
532
  # @param context [Spree::AgentTools::Context]
335
533
  # @return [Array<Entry>]
336
534
  def available_for(context)
337
- all.select { |entry| context.permitted?(entry.permission) }
535
+ all.select { |entry| entry.readable_by?(context) }
338
536
  end
339
537
 
340
538
  private
@@ -3,10 +3,10 @@ require 'spree/agent_tools/context'
3
3
  require 'spree/agent_tools/resource_map'
4
4
  require 'spree/agent_tools/api_dispatch'
5
5
  require 'spree/agent_tools/membership_map'
6
- require 'spree/agent_tools/workflow_endpoints'
7
6
  require 'spree/agent_tools/record_summary'
8
- require 'spree/agent_tools/workflow_schema'
9
- require 'spree/agent_tools/workflow_tool'
7
+ require 'spree/agent_tools/legacy_tools'
8
+ require 'spree/agent_tools/operation_catalog'
9
+ require 'spree/agent_tools/operation_tool'
10
10
  require 'spree/agent_tools/default_catalog'
11
11
 
12
12
  module Spree
@@ -12,43 +12,48 @@ module Spree
12
12
  injection_points = base::INJECTION_POINTS_WITH_DEFAULTS.keys.freeze
13
13
  base.const_set(:INJECTION_POINTS, injection_points)
14
14
 
15
- injection_points.each do |point|
16
- # Original getter - returns raw value (string, class, or proc result)
17
- # BACKWARDS COMPATIBLE: Spree::Dependencies.foo.constantize still works
18
- base.attr_reader(point)
19
-
20
- # Setter with override tracking
21
- # BACKWARDS COMPATIBLE: Spree::Dependencies.foo = "MyClass" still works
22
- base.define_method("#{point}=") do |value|
23
- @overrides ||= {}
24
- @overrides[point] = {
25
- value: value,
26
- source: find_caller_source,
27
- set_at: Time.current
28
- }
29
- # Clear memoized class when value changes
30
- remove_instance_variable("@#{point}_resolved") if instance_variable_defined?("@#{point}_resolved")
31
- instance_variable_set("@#{point}", value)
32
- end
33
-
34
- # Returns resolved class with memoization
35
- # Usage: Spree::Dependencies.foo_class or Spree.foo
36
- base.define_method("#{point}_class") do
37
- return instance_variable_get("@#{point}_resolved") if instance_variable_defined?("@#{point}_resolved")
38
-
39
- value = send(point)
40
- resolved = case value
41
- when String then value.constantize
42
- when Proc then value.call.then { |v| v.is_a?(String) ? v.constantize : v }
43
- else value
44
- end
45
- # An injection point may legitimately have no default — the class is
46
- # supplied by an optional gem (search_product_presenter). Leave it
47
- # unmemoized so installing the gem later still takes effect.
48
- return nil if resolved.nil?
49
- instance_variable_set("@#{point}_resolved", resolved)
50
- resolved
51
- end
15
+ injection_points.each { |point| define_injection_point(base, point) }
16
+ end
17
+
18
+ # Defines the reader, the tracked setter and the resolving `_class` reader
19
+ # for one injection point, on a class (core points) or on one instance's
20
+ # singleton class (points an extension registers).
21
+ def self.define_injection_point(target, point)
22
+ # Original getter - returns raw value (string, class, or proc result)
23
+ # BACKWARDS COMPATIBLE: Spree::Dependencies.foo.constantize still works
24
+ target.attr_reader(point)
25
+
26
+ # Setter with override tracking
27
+ # BACKWARDS COMPATIBLE: Spree::Dependencies.foo = "MyClass" still works
28
+ target.define_method("#{point}=") do |value|
29
+ @overrides ||= {}
30
+ @overrides[point] = {
31
+ value: value,
32
+ source: find_caller_source,
33
+ set_at: Time.current
34
+ }
35
+ # Clear memoized class when value changes
36
+ remove_instance_variable("@#{point}_resolved") if instance_variable_defined?("@#{point}_resolved")
37
+ instance_variable_set("@#{point}", value)
38
+ end
39
+
40
+ # Returns resolved class with memoization
41
+ # Usage: Spree::Dependencies.foo_class or Spree.foo
42
+ target.define_method("#{point}_class") do
43
+ return instance_variable_get("@#{point}_resolved") if instance_variable_defined?("@#{point}_resolved")
44
+
45
+ value = send(point)
46
+ resolved = case value
47
+ when String then value.constantize
48
+ when Proc then value.call.then { |v| v.is_a?(String) ? v.constantize : v }
49
+ else value
50
+ end
51
+ # An injection point may legitimately have no default — the class is
52
+ # supplied by an optional gem (search_product_presenter). Leave it
53
+ # unmemoized so installing the gem later still takes effect.
54
+ return nil if resolved.nil?
55
+ instance_variable_set("@#{point}_resolved", resolved)
56
+ resolved
52
57
  end
53
58
  end
54
59
 
@@ -56,6 +61,53 @@ module Spree
56
61
  set_default_values
57
62
  end
58
63
 
64
+ # Adds an injection point an extension owns, so its own workflows and
65
+ # services can be swapped by a host app exactly like core's:
66
+ #
67
+ # Spree::Dependencies.register(:quote_send_workflow, 'MyExtension::Quotes::Send')
68
+ # Spree.quote_send_workflow # => MyExtension::Quotes::Send
69
+ #
70
+ # Register from an initializer. A host app that sets the key afterwards
71
+ # replaces the default, as with any core key. Registering a key that
72
+ # already exists raises, so two gems cannot silently claim one name.
73
+ #
74
+ # @param point [Symbol, String]
75
+ # @param default [String, Class, Proc] class name preferred, so the
76
+ # class loads on first use
77
+ # @return [Symbol] the key
78
+ def register(point, default)
79
+ point = point.to_sym
80
+ raise ArgumentError, "#{point} is already a dependency" if injection_point?(point)
81
+ # `cart_add_item_workflow_class` would shadow the resolving reader core
82
+ # defines for `cart_add_item_workflow`, a key `Spree` already answers
83
+ # itself (`search_provider`) would never be read, and an existing
84
+ # setter would lose its own behaviour to the tracked one.
85
+ names = [point, "#{point}_class", "#{point}="]
86
+ if [self, Spree].any? { |owner| names.any? { |name| owner.respond_to?(name, true) } }
87
+ raise ArgumentError, "#{point} would replace an existing method"
88
+ end
89
+
90
+ # Evaluated first, so a default that raises leaves nothing registered.
91
+ value = default.respond_to?(:call) ? default.call : default
92
+ registered_points[point] = default
93
+ Spree::DependenciesHelper.define_injection_point(singleton_class, point)
94
+ instance_variable_set("@#{point}", value)
95
+ point
96
+ end
97
+
98
+ # Core's injection points plus the ones extensions registered.
99
+ #
100
+ # @return [Array<Symbol>]
101
+ def injection_points
102
+ self.class::INJECTION_POINTS + registered_points.keys
103
+ end
104
+
105
+ # @param point [Symbol, String]
106
+ # @return [Boolean]
107
+ def injection_point?(point)
108
+ injection_points.include?(point.to_sym)
109
+ end
110
+
59
111
  # Returns hash of all overridden dependencies with metadata
60
112
  def overrides
61
113
  @overrides || {}
@@ -73,8 +125,8 @@ module Spree
73
125
 
74
126
  # Returns array of all dependencies with current values and metadata
75
127
  def current_values
76
- self.class::INJECTION_POINTS.map do |point|
77
- default = self.class::INJECTION_POINTS_WITH_DEFAULTS[point]
128
+ injection_points.map do |point|
129
+ default = self.class::INJECTION_POINTS_WITH_DEFAULTS.fetch(point) { registered_points[point] }
78
130
  default_val = default.respond_to?(:call) ? default.call : default
79
131
  current = send(point)
80
132
 
@@ -94,7 +146,7 @@ module Spree
94
146
  # Raises Spree::DependencyError if any dependency is invalid
95
147
  def validate!
96
148
  errors = []
97
- self.class::INJECTION_POINTS.each do |point|
149
+ injection_points.each do |point|
98
150
  send("#{point}_class")
99
151
  rescue NameError => e
100
152
  errors << { name: point, value: send(point), error: e.message }
@@ -106,6 +158,10 @@ module Spree
106
158
 
107
159
  private
108
160
 
161
+ def registered_points
162
+ @registered_points ||= {}
163
+ end
164
+
109
165
  def set_default_values
110
166
  self.class::INJECTION_POINTS_WITH_DEFAULTS.each do |injection_point, default_value|
111
167
  value = default_value.respond_to?(:call) ? default_value.call : default_value
@@ -10,6 +10,7 @@ module Spree
10
10
  :dependencies,
11
11
  :payment_methods,
12
12
  :adjusters,
13
+ :cart_copiers,
13
14
  :media_viewable_types,
14
15
  :default_tax_provider,
15
16
  :tax_providers,
@@ -79,7 +80,7 @@ module Spree
79
80
  %i[subscribers actor_classes commission_rules delivery_method_rules seller_requirements
80
81
  delivery_rate_providers tax_providers pricing_providers inventory_providers
81
82
  payout_providers digital_asset_providers delivery_profile_types pickup_point_providers
82
- maintenance_tasks].each do |registry|
83
+ maintenance_tasks cart_copiers].each do |registry|
83
84
  app.config.spree[registry] = []
84
85
  end
85
86
  app.config.spree.line_item_comparison_hooks = Set.new
@@ -605,6 +606,16 @@ module Spree
605
606
  Rails.autoloaders.main.do_not_eager_load(*DEPRECATED_ALIAS_FILES.map { |path| root.join(path) })
606
607
  end
607
608
 
609
+ # Hands reported errors to the diagnostics error log, resolving the
610
+ # class per call so a development reload picks up the new one.
611
+ module DiagnosticsErrorSubscriber
612
+ def self.report(...) = Spree::Diagnostics::ErrorLog.new.report(...)
613
+ end
614
+
615
+ initializer 'spree.diagnostics.error_log' do
616
+ Rails.error.subscribe(DiagnosticsErrorSubscriber)
617
+ end
618
+
608
619
  # filter sensitive information during logging
609
620
  initializer 'spree.params.filter' do |app|
610
621
  app.config.filter_parameters += [
@@ -1,5 +1,5 @@
1
1
  module Spree
2
- VERSION = '6.0.2'.freeze
2
+ VERSION = '6.0.4'.freeze
3
3
 
4
4
  def self.version
5
5
  VERSION
data/lib/spree/core.rb CHANGED
@@ -170,6 +170,17 @@ module Spree
170
170
  @@search_provider = value.to_s
171
171
  end
172
172
 
173
+ # Sections of the diagnostics report (see Spree::Diagnostics), as class
174
+ # names so an initializer can add one before its class is autoloaded.
175
+ #
176
+ # Spree.diagnostics_sections << 'MyGem::DiagnosticsSection'
177
+ #
178
+ # @return [Array<String>]
179
+ def self.diagnostics_sections
180
+ @@diagnostics_sections ||= %w[Platform Runtime Infrastructure Preferences].
181
+ map { |name| "Spree::Diagnostics::Sections::#{name}" }
182
+ end
183
+
173
184
  # Tax ID validators, keyed by registration kind.
174
185
  #
175
186
  # Core ships one, for +eu_vat+, and it checks format only — the shape of an EU
@@ -323,6 +334,22 @@ module Spree
323
334
  # @return [Array<Class>]
324
335
  singleton_class.delegate :tax_providers, :tax_providers=, to: :spree_config
325
336
 
337
+ # Extensions that copy their own cart data onto the order a cart becomes.
338
+ # Each entry is a class with a class-level +call(cart:, order:,
339
+ # line_item_map:)+ (a class, so it is re-resolved when code reloads in
340
+ # development; see {.refresh_provider_registries!}), where the map
341
+ # pairs each cart line item with its copy on the order. Both copies run them
342
+ # — checkout ({Spree::Carts::Complete}) and the draft-order copy
343
+ # ({Spree::Orders::CreateFromCart}) — inside their transaction, once the
344
+ # order's line items exist, so an entry that raises rolls the order back.
345
+ #
346
+ # Append, never assign, so an extension does not drop what another added:
347
+ #
348
+ # Spree.cart_copiers << MyApp::CopyEngravings
349
+ #
350
+ # @return [Array<Class>]
351
+ singleton_class.delegate :cart_copiers, :cart_copiers=, to: :spree_config
352
+
326
353
  # Pricing engines a store can be pointed at. Connector gems append their own,
327
354
  # so a merchant picks from what is actually installed.
328
355
  #
@@ -400,7 +427,8 @@ module Spree
400
427
  def self.refresh_provider_registries!
401
428
  [Rails.application.config.spree.delivery_rate_providers,
402
429
  Rails.application.config.spree.fulfillment_providers,
403
- Rails.application.config.spree.pickup_point_providers].compact.each do |registry|
430
+ Rails.application.config.spree.pickup_point_providers,
431
+ Rails.application.config.spree.cart_copiers].compact.each do |registry|
404
432
  registry.map! { |entry| entry.is_a?(Module) && entry.name ? entry.name.constantize : entry }
405
433
  end
406
434
  end
@@ -603,7 +631,7 @@ module Spree
603
631
  def core_dependency?(name)
604
632
  return false unless defined?(Spree::Dependencies)
605
633
 
606
- Spree::Dependencies.class::INJECTION_POINTS.include?(name) ||
634
+ Spree::Dependencies.injection_point?(name) ||
607
635
  Spree::Dependencies.class::LEGACY_WORKFLOW_KEYS.key?(name) ||
608
636
  Spree::Dependencies.class::LEGACY_SERVICE_KEYS.key?(name) ||
609
637
  Spree::Dependencies.class::RENAMED_SERVICE_KEYS.key?(name)
@@ -429,7 +429,15 @@ module Spree
429
429
  metric :orders_lifetime, sql: LIFETIME_ORDERS_SUBQUERY, base: :orders, format: :integer,
430
430
  requires_grouping: :customer,
431
431
  subject: -> { Spree.customer_class }, key_scope: 'read_customers'
432
+ end
433
+ install_dimensions(registry)
434
+ install_axes(registry)
435
+ install_counters(registry)
436
+ end
432
437
 
438
+ # Dimensions of the orders and line items bases.
439
+ def self.install_dimensions(registry)
440
+ registry.instance_eval do
433
441
  dimension :completed_at, base: :orders, column: :completed_at, type: :time,
434
442
  grains: %i[hour day week month]
435
443
  dimension :payment_status, base: :orders, column: :payment_status,
@@ -555,7 +563,12 @@ module Spree
555
563
  }]
556
564
  end
557
565
  }
566
+ end
567
+ end
558
568
 
569
+ # Dimensions of the carts, promotions, payments and stock bases.
570
+ def self.install_axes(registry)
571
+ registry.instance_eval do
559
572
  # ---- cart axes ----
560
573
 
561
574
  dimension :started_at, base: :carts, column: :created_at, type: :time,
@@ -650,7 +663,11 @@ module Spree
650
663
  [location.id, { id: location.prefixed_id, label: location.name, meta: {} }]
651
664
  end
652
665
  }
666
+ end
667
+ end
653
668
 
669
+ def self.install_counters(registry)
670
+ registry.instance_eval do
654
671
  # ---- counters ----
655
672
  #
656
673
  # What needs attention right now. Order counters honour the channel
@@ -697,19 +714,22 @@ module Spree
697
714
  link: { resource: 'claims',
698
715
  filters: [{ field: 'status', operator: 'in', value: OPEN_CLAIM_STATUSES.join(',') }] }
699
716
 
717
+ # Variants, not stock levels: a SKU stocked in one warehouse and
718
+ # absent from another is not out of stock, and counting one row per
719
+ # location would report every such pair as a problem.
700
720
  counter :low_stock_items,
701
721
  subject: -> { Spree::StockLevel }, key_scope: 'read_stock',
702
- count: lambda { |store, channel:|
703
- STORE_STOCK.call(store).low_stock(store.preferred_low_stock_threshold).count
722
+ count: lambda { |store, **|
723
+ STORE_STOCK.call(store).low_stock_overall(store.preferred_low_stock_threshold).distinct.count(:variant_id)
704
724
  },
705
725
  link: { resource: 'inventory',
706
- filters: [{ field: 'stock_status', operator: 'in', value: 'low_stock' }] }
726
+ filters: [{ field: 'stock_status', operator: 'in', value: 'low_stock_overall' }] }
707
727
 
708
728
  counter :out_of_stock_items,
709
729
  subject: -> { Spree::StockLevel }, key_scope: 'read_stock',
710
- count: ->(store, channel:) { STORE_STOCK.call(store).out_of_stock.count },
730
+ count: ->(store, **) { STORE_STOCK.call(store).out_of_stock_overall.distinct.count(:variant_id) },
711
731
  link: { resource: 'inventory',
712
- filters: [{ field: 'stock_status', operator: 'in', value: 'out_of_stock' }] }
732
+ filters: [{ field: 'stock_status', operator: 'in', value: 'out_of_stock_overall' }] }
713
733
  end
714
734
  end
715
735
  end
@@ -1,5 +1,17 @@
1
1
  require 'spree/testing_support/common_rake'
2
2
 
3
+ # `rake spree:openapi:generate` writes the extension's openapi/*.yaml from its
4
+ # rswag specs, and `rake spree:sdk:serializer_types` the response types of a
5
+ # package that extends the SDKs (both run by `spree sdk generate`).
6
+ begin
7
+ require 'spree/api/testing_support/openapi_tasks'
8
+ require 'spree/api/sdk_types_task'
9
+ Spree::Api::SdkTypesTask.new
10
+ rescue LoadError
11
+ # An extension without spree_api has no API to document. These files load
12
+ # nothing else, so this is the only thing that can be missing.
13
+ end
14
+
3
15
  desc 'Generates a dummy app for testing an extension'
4
16
  namespace :extension do
5
17
  task :test_app, [:options] do |_t, args|