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,121 @@
1
+ module Spree
2
+ class Diagnostics
3
+ # The sections core ships. Extensions add their own through
4
+ # {Spree.diagnostics_sections}.
5
+ module Sections
6
+ class Platform < Section
7
+ def title = 'Spree'
8
+
9
+ def rows
10
+ {
11
+ 'Version' => -> { ::Spree.version },
12
+ 'Gems' => -> { Stack.spree_gems.map { |name, version| "#{name} #{version}" } },
13
+ 'Other gems built on Spree' => -> { extensions }
14
+ }
15
+ end
16
+
17
+ private
18
+
19
+ # Only a count: the other gems built on Spree are often the merchant's
20
+ # own, private ones, and their names don't belong in a public issue.
21
+ def extensions
22
+ listed = Stack.spree_gems
23
+ Gem.loaded_specs.values.count do |spec|
24
+ !listed.key?(spec.name) && (Stack.spree_gem?(spec) || spec.runtime_dependencies.any? { |dependency| listed.key?(dependency.name) })
25
+ end
26
+ end
27
+ end
28
+
29
+ class Runtime < Section
30
+ def title = 'Runtime'
31
+
32
+ def rows
33
+ {
34
+ 'Ruby' => -> { "#{RUBY_VERSION} (#{RUBY_PLATFORM})" },
35
+ 'Rails' => -> { Rails.version },
36
+ 'Environment' => -> { Rails.env },
37
+ 'Operating system' => -> { operating_system },
38
+ 'Web server' => -> { web_server }
39
+ }
40
+ end
41
+
42
+ private
43
+
44
+ def operating_system
45
+ uname = Etc.uname
46
+ "#{uname[:sysname]} #{uname[:release]} #{uname[:machine]}"
47
+ end
48
+
49
+ def web_server
50
+ "Puma #{::Puma::Const::PUMA_VERSION}" if defined?(::Puma::Const::PUMA_VERSION)
51
+ end
52
+ end
53
+
54
+ class Infrastructure < Section
55
+ def title = 'Infrastructure'
56
+
57
+ def rows
58
+ {
59
+ 'Database' => -> { [Stack.database, database_version].compact.join(' ') },
60
+ 'Queue adapter' => -> { ActiveJob::Base.queue_adapter_name },
61
+ 'Cache store' => -> { Rails.cache.class.name.demodulize.underscore },
62
+ 'File storage' => -> { Rails.application.config.active_storage.service }
63
+ }
64
+ end
65
+
66
+ private
67
+
68
+ # PostgreSQL reports 180006 for 18.6.
69
+ def database_version
70
+ version = ActiveRecord::Base.connection.database_version
71
+ version.is_a?(Integer) ? "#{version / 10_000}.#{version % 10_000}" : version.to_s
72
+ end
73
+ end
74
+
75
+ # Settings changed from their defaults. Only flags, numbers and
76
+ # fixed-choice strings are shown: free-form strings can hold URLs,
77
+ # names or credentials, so they are never reported, whatever they are.
78
+ class Preferences < Section
79
+ REPORTABLE_TYPES = %i[boolean integer decimal].freeze
80
+
81
+ def title = 'Changed settings'
82
+
83
+ def rows
84
+ config_rows.merge(store_rows)
85
+ end
86
+
87
+ private
88
+
89
+ def config_rows
90
+ config = ::Spree::Config
91
+ config.class.types.each_with_object({}) do |(name, type), rows|
92
+ next if config.class.deprecations[name] || REPORTABLE_TYPES.exclude?(type)
93
+
94
+ rows["config.#{name}"] = lambda do
95
+ value = config.get(name)
96
+ value unless value == config.class.defaults[name]
97
+ end
98
+ end
99
+ end
100
+
101
+ def store_rows
102
+ store.class.preference_definitions.each_with_object({}) do |(name, definition), rows|
103
+ next unless reportable?(name, definition)
104
+
105
+ rows["store.#{name}"] = lambda do
106
+ value = store.get_preference(name)
107
+ value unless value == store.preference_default(name)
108
+ end
109
+ end
110
+ end
111
+
112
+ def reportable?(name, definition)
113
+ return false if definition[:internal] || definition[:deprecated]
114
+
115
+ REPORTABLE_TYPES.include?(definition[:type]) ||
116
+ (definition[:type] == :string && store.preference_choices(name).is_a?(Array))
117
+ end
118
+ end
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,73 @@
1
+ module Spree
2
+ class Diagnostics
3
+ # The installation's stack and rough size, shared by the update check's
4
+ # heartbeat and the diagnostics report so the two never describe the same
5
+ # installation differently.
6
+ module Stack
7
+ # Order-of-magnitude buckets: enough to tell a hobby install from a large
8
+ # merchant, never an exact figure.
9
+ BUCKETS = {
10
+ 0..0 => '0',
11
+ 1..9 => '1-9',
12
+ 10..99 => '10-99',
13
+ 100..999 => '100-999',
14
+ 1_000..9_999 => '1k-9k',
15
+ 10_000..99_999 => '10k-99k'
16
+ }.freeze
17
+ LARGEST_BUCKET = '100k+'.freeze
18
+ SPREE_URL = %r{\Ahttps?://(www\.)?(spreecommerce\.org|github\.com/spree/)}
19
+
20
+ module_function
21
+
22
+ # @return [String] the database adapter, e.g. +postgresql+
23
+ def database
24
+ ActiveRecord::Base.connection_db_config.adapter
25
+ end
26
+
27
+ # Spree's own gems and published Spree extensions, by name. A private
28
+ # gem named spree_* is left out: its name is the merchant's business.
29
+ #
30
+ # @return [Hash{String => String}] gem name => version
31
+ def spree_gems
32
+ Gem.loaded_specs.values.select { |spec| spree_gem?(spec) && public_gem?(spec) }.
33
+ sort_by(&:name).to_h { |spec| [spec.name, spec.version.to_s] }
34
+ end
35
+
36
+ # @param spec [Gem::Specification]
37
+ # @return [Boolean]
38
+ def spree_gem?(spec)
39
+ spec.name == 'spree' || spec.name.start_with?('spree_')
40
+ end
41
+
42
+ # Whether a gem's name can appear in a public bug report: one of Spree's
43
+ # own, or one installed from rubygems.org. Gems from a path, git or a
44
+ # private gem server are often the merchant's own code.
45
+ #
46
+ # @param spec [Gem::Specification]
47
+ # @return [Boolean]
48
+ def public_gem?(spec)
49
+ return true if [spec.homepage, *spec.metadata.values].any? { |url| url.to_s.match?(SPREE_URL) }
50
+
51
+ source = spec.respond_to?(:source) ? spec.source : nil
52
+ source.is_a?(Bundler::Source::Rubygems) && source.remotes.all? { |remote| remote.host == 'rubygems.org' }
53
+ end
54
+
55
+ # @return [Boolean] whether this installation serves an admin dashboard
56
+ def dashboard_served?
57
+ (defined?(Spree::Dashboard) && Spree::Dashboard.dist_path.present?) || Spree::Config.dashboard_url.present?
58
+ end
59
+
60
+ # @param count [Integer]
61
+ # @return [String]
62
+ def bucket(count)
63
+ BUCKETS.find { |range, _| range.cover?(count) }&.last || LARGEST_BUCKET
64
+ end
65
+
66
+ # @return [String, nil] nil when the installation has no sellers
67
+ def seller_bucket
68
+ count = Spree::Seller.count
69
+ bucket(count) if count.positive?
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,132 @@
1
+ module Spree
2
+ # An anonymised description of this installation for bug reports: versions,
3
+ # stack, store setup by prefixed ID, providers, changed settings and recent
4
+ # Spree errors. The rake task, the Admin API and the CLI all render this one
5
+ # report, so what a maintainer reads is the same wherever it came from.
6
+ #
7
+ # report = Spree::Diagnostics.report(store: Spree::Current.store)
8
+ # puts report.to_markdown
9
+ class Diagnostics
10
+ ISSUE_URL = 'https://github.com/spree/spree/issues/new?template=bug_report.yml'.freeze
11
+ # GitHub refuses very long URLs; past this the issue form opens empty and
12
+ # the report is pasted by hand.
13
+ MAX_ISSUE_URL_LENGTH = 6000
14
+
15
+ # A built report. Never persisted.
16
+ class Report
17
+ attr_reader :generated_at, :sections, :errors
18
+
19
+ def initialize(generated_at:, sections:, errors:)
20
+ @generated_at = generated_at
21
+ @sections = sections
22
+ @errors = errors
23
+ end
24
+
25
+ # @return [String] Spree version, for the report's headline
26
+ def spree_version
27
+ Spree.version
28
+ end
29
+
30
+ # @return [Hash]
31
+ def to_h
32
+ { generated_at: generated_at.iso8601, spree_version: spree_version, sections: sections, errors: errors,
33
+ markdown: to_markdown, issue_url: issue_url, issue_prefilled: issue_prefilled? }
34
+ end
35
+
36
+ # A new GitHub issue with the report filled in, or the empty form when
37
+ # the report is too long for a URL.
38
+ #
39
+ # @return [String]
40
+ def issue_url
41
+ @issue_url ||= begin
42
+ prefilled = "#{ISSUE_URL}&environment=#{ERB::Util.url_encode(to_markdown)}"
43
+ prefilled.length <= MAX_ISSUE_URL_LENGTH ? prefilled : ISSUE_URL
44
+ end
45
+ end
46
+
47
+ # @return [Boolean]
48
+ def issue_prefilled?
49
+ issue_url != ISSUE_URL
50
+ end
51
+
52
+ # GitHub-flavoured Markdown, folded into a <details> block so it doesn't
53
+ # take over the issue it is pasted into.
54
+ #
55
+ # @return [String]
56
+ def to_markdown
57
+ @to_markdown ||= render_markdown
58
+ end
59
+
60
+ private
61
+
62
+ def render_markdown
63
+ lines = ['<details>', "<summary>Spree #{spree_version} diagnostics (#{generated_at.iso8601})</summary>", '']
64
+
65
+ sections.each do |section|
66
+ next if section[:rows].empty?
67
+
68
+ lines.push("**#{section[:title]}**", '', '| | |', '| --- | --- |')
69
+ section[:rows].each { |row| lines << "| #{escape(row[:label])} | #{escape(row[:value])} |" }
70
+ lines << ''
71
+ end
72
+
73
+ if errors
74
+ lines.push('**Recent errors**', '')
75
+ lines << 'None recorded.' if errors.empty?
76
+ errors.each do |error|
77
+ lines << "- `#{error[:error_class]}` × #{error[:count]}, last #{error[:last_seen_at]}#{" (#{error[:source]})" if error[:source]}"
78
+ error[:frames].each { |frame| lines << " - `#{frame}`" }
79
+ end
80
+ lines << ''
81
+ end
82
+
83
+ lines << '</details>'
84
+ lines.join("\n")
85
+ end
86
+
87
+ def escape(value)
88
+ value.to_s.gsub(/[\\|]/) { |char| "\\#{char}" }.gsub(/[\r\n]+/, ' ')
89
+ end
90
+ end
91
+
92
+ class << self
93
+ # @param store [Spree::Store]
94
+ # @param extra_sections [Array<Hash>] what only the caller can see, as
95
+ # `{ title:, rows: { label => value } }` — the CLI's tooling, the
96
+ # dashboard's browser
97
+ # @param errors [Boolean] false to leave recent errors out, as
98
+ # +spree info+ does: it runs in its own process, which rarely sees
99
+ # the server's error log
100
+ # @return [Spree::Diagnostics::Report]
101
+ def report(store: Spree::Store.default, extra_sections: [], errors: true)
102
+ Report.new(generated_at: Time.current, errors: (recent_errors if errors),
103
+ sections: sections_for(store) + extra_sections.map { |section| extra_section(section) })
104
+ end
105
+
106
+ private
107
+
108
+ def sections_for(store)
109
+ Spree.diagnostics_sections.filter_map do |class_name|
110
+ section = class_name.to_s.constantize.new(store)
111
+ { key: section.key, title: section.title, rows: section.to_rows }
112
+ rescue StandardError
113
+ { key: class_name.to_s.demodulize.underscore, title: class_name.to_s.demodulize.titleize,
114
+ rows: [{ label: 'Error', value: 'This section could not be read' }] }
115
+ end
116
+ end
117
+
118
+ def extra_section(section)
119
+ title = section[:title].to_s
120
+ rows = section[:rows].to_h.map { |label, value| { label: label.to_s, value: value.to_s } }
121
+ { key: title.parameterize(separator: '_'), title: title, rows: rows }
122
+ end
123
+
124
+ # A failing cache must not take the rest of the report down with it.
125
+ def recent_errors
126
+ ErrorLog.entries.map { |entry| entry.except(:fingerprint) }
127
+ rescue StandardError
128
+ []
129
+ end
130
+ end
131
+ end
132
+ end
@@ -2,7 +2,8 @@ module Spree
2
2
  module Newsletter
3
3
  class Subscribe
4
4
  def initialize(email:, current_user: nil, current_store: nil, redirect_url: nil)
5
- @email = email
5
+ @submitted_email = email.to_s.strip
6
+ @email = @submitted_email.downcase
6
7
  @current_user = current_user
7
8
  @current_store = current_store || Spree::Store.current
8
9
  @redirect_url = redirect_url
@@ -20,7 +21,7 @@ module Spree
20
21
 
21
22
  Spree::Newsletter::LinkUser.new(subscriber: subscriber, user: known_user).call
22
23
 
23
- if subscriber.email == current_user&.email
24
+ if current_user && subscriber.email.to_s.casecmp?(current_user.email.to_s)
24
25
  # User's email is already verified by login — skip the double opt-in.
25
26
  Spree::Newsletter::Verify.new(subscriber: subscriber).call
26
27
  end
@@ -32,7 +33,7 @@ module Spree
32
33
 
33
34
  private
34
35
 
35
- attr_reader :email, :current_user, :current_store, :redirect_url
36
+ attr_reader :email, :submitted_email, :current_user, :current_store, :redirect_url
36
37
 
37
38
  def publish_subscription_requested
38
39
  event_name = 'newsletter_subscriber.subscription_requested'
@@ -62,7 +63,10 @@ module Spree
62
63
  @known_user ||= if current_user&.email.to_s.casecmp?(email.to_s)
63
64
  current_user
64
65
  else
65
- Spree.customer_class.find_by(email: email)
66
+ # Customer emails are not downcased on save, so try the
67
+ # address as submitted before the normalized form.
68
+ Spree.customer_class.find_by(email: submitted_email) ||
69
+ Spree.customer_class.find_by(email: email)
66
70
  end
67
71
  end
68
72
  end
@@ -25,7 +25,8 @@ module Spree
25
25
  order = build_order(cart, customer: customer, created_by: created_by)
26
26
  order.save!
27
27
 
28
- copy_line_items(cart, order)
28
+ line_item_map = copy_line_items(cart, order)
29
+ Spree.cart_copiers.each { |copier| copier.call(cart: cart, order: order, line_item_map: line_item_map) }
29
30
  estimate_taxes(order)
30
31
  build_fulfillments(order)
31
32
  order.recalculate_totals!
@@ -60,12 +61,15 @@ module Spree
60
61
  )
61
62
  end
62
63
 
64
+ # @return [Hash{Spree::LineItem => Spree::LineItem}] cart line item → its
65
+ # copy on the order, the map {Spree.cart_copiers} receive
63
66
  def copy_line_items(cart, order)
64
- cart.line_items.each do |cart_line_item|
67
+ cart.line_items.to_a.index_with do |cart_line_item|
65
68
  line_item = order.line_items.new(cart_line_item.attributes.slice(*LINE_ITEM_COPIED_ATTRIBUTES))
66
69
  # Estimated once for the batch below, not once per line.
67
70
  line_item.skip_tax_estimation = true
68
71
  line_item.save!
72
+ line_item
69
73
  end
70
74
  end
71
75
 
@@ -11,12 +11,23 @@ module Spree
11
11
  # @param options [Hash] accepted for signature compatibility and ignored
12
12
  # @return [Spree::ServiceModule::Result] value is the removed line item
13
13
  def call(order:, line_item:, options: {})
14
- result = Spree.order_upsert_items_workflow.call(
15
- order: order,
16
- items: [{ variant_id: line_item.variant_id, quantity: 0 }]
17
- )
14
+ result = nil
15
+ # A savepoint: a caller's transaction (the API's order lock) joins the
16
+ # workflow's own, so a late rejection would otherwise commit the removal.
17
+ ActiveRecord::Base.transaction(requires_new: true) do
18
+ result = Spree.order_upsert_items_workflow.call(
19
+ order: order,
20
+ items: [{ variant_id: line_item.variant_id, quantity: 0 }]
21
+ )
22
+ raise ActiveRecord::Rollback if result.failure?
23
+ end
24
+ return failure(line_item, result.error) if result.failure?
18
25
 
19
- result.success? ? success(line_item) : failure(line_item, result.error)
26
+ # The order workflow leaves totals to its caller.
27
+ Spree::Orders::Recalculate.call(order: order)
28
+ order.update_statuses!
29
+
30
+ success(line_item)
20
31
  end
21
32
  end
22
33
  end
@@ -9,6 +9,7 @@ module Spree
9
9
  def add_memberships(groups, products)
10
10
  group_ids = groups.pluck(:id)
11
11
  product_ids = products.pluck(:id)
12
+ existing = membership_class.where(group_key => group_ids, product_id: product_ids).ids
12
13
  # Every group's current size in one grouped count, rather than a probe
13
14
  # per group for the position to append at.
14
15
  sizes = membership_class.where(group_key => group_ids).group(group_key).count
@@ -24,15 +25,23 @@ module Spree
24
25
  end
25
26
  membership_class.insert_all(rows)
26
27
 
28
+ created = membership_class.where(group_key => group_ids, product_id: product_ids).where.not(id: existing)
29
+
27
30
  refresh_after_membership_change(group_ids, products)
31
+ publish_membership_events(created, 'created')
28
32
  end
29
33
 
30
34
  # Removes the products, then re-packs the remaining positions from 1.
31
35
  def remove_memberships(groups, products)
32
36
  group_ids = groups.pluck(:id)
37
+ product_ids = products.pluck(:id)
38
+ deleted = []
33
39
 
34
40
  ApplicationRecord.transaction do
35
- membership_class.where(group_key => group_ids, product_id: products.pluck(:id)).delete_all
41
+ # Ordered so two callers queue for the same rows in the same sequence rather than deadlocking on each other.
42
+ deleted = membership_class.where(group_key => group_ids, product_id: product_ids).order(:id).lock.to_a
43
+
44
+ membership_class.where(group_key => group_ids, product_id: product_ids).delete_all
36
45
 
37
46
  # What survived the delete, for every group in one read.
38
47
  remaining = membership_class.where(group_key => group_ids).order(:position).pluck(group_key, :product_id).
@@ -50,6 +59,17 @@ module Spree
50
59
  end
51
60
 
52
61
  refresh_after_membership_change(group_ids, products)
62
+ publish_membership_events(deleted, 'deleted')
63
+ end
64
+
65
+ def publish_membership_events(memberships, action)
66
+ memberships = memberships.to_a
67
+ return if memberships.empty?
68
+
69
+ ActiveRecord::Associations::Preloader.new(records: memberships, associations: { product: :store }).call
70
+
71
+ name = "#{membership_class.model_name.element}.#{action}"
72
+ memberships.each { |membership| membership.publish_event(name) }
53
73
  end
54
74
 
55
75
  # Bulk writes skip the join model's callbacks, so counters, caches and the
@@ -136,8 +136,9 @@ module Spree
136
136
  scoped_ids = store.products.where(id: product_ids).ids
137
137
  return [] if scoped_ids.empty?
138
138
 
139
- existing = Spree::ProductCategory.where(product_id: scoped_ids, category_id: category_ids).
140
- pluck(:product_id, :category_id).to_set
139
+ existing_rows = Spree::ProductCategory.where(product_id: scoped_ids, category_id: category_ids).
140
+ pluck(:id, :product_id, :category_id)
141
+ existing = existing_rows.to_set { |_id, product_id, category_id| [product_id, category_id] }
141
142
 
142
143
  # acts_as_list scopes position per category here (unlike option types,
143
144
  # which scope per product), so each category continues its own sequence.
@@ -160,8 +161,17 @@ module Spree
160
161
  return [] if rows.empty?
161
162
 
162
163
  Spree::ProductCategory.insert_all(rows)
164
+ publish_categorized_events(scoped_ids, category_ids, existing_rows.map(&:first))
165
+
163
166
  rows.pluck(:product_id).uniq
164
167
  end
168
+
169
+ def publish_categorized_events(product_ids, category_ids, existing_ids)
170
+ created = Spree::ProductCategory.where(product_id: product_ids, category_id: category_ids).
171
+ where.not(id: existing_ids)
172
+
173
+ created.each { |membership| membership.publish_event('product_category.created') }
174
+ end
165
175
  end
166
176
  end
167
177
  end
@@ -9,22 +9,28 @@ module Spree
9
9
  # @param product [Spree::Product]
10
10
  # @return [Spree::ServiceModule::Base::Result]
11
11
  def call(product:)
12
- return unless product.present?
12
+ return if product.blank?
13
13
 
14
14
  collections_to_remove = []
15
15
  collections_to_add = []
16
16
 
17
17
  # existing memberships that no longer match (tags/prices changed)
18
- product.collections.automatic.includes(:rules).each do |collection|
18
+ product.collections.automatic.includes(:rules).find_each do |collection|
19
19
  collections_to_remove << collection unless collection.products_matching_rules.ids.include?(product.id)
20
20
  end
21
21
 
22
+ # Held before the delete: the rows are gone by the time their deleted
23
+ # events can be published.
24
+ removed_rows = []
25
+
22
26
  if collections_to_remove.any?
23
- Spree::ProductCollection.where(collection: collections_to_remove, product: product).delete_all
27
+ scope = Spree::ProductCollection.where(collection: collections_to_remove, product: product)
28
+ removed_rows = scope.to_a
29
+ scope.delete_all
24
30
  end
25
31
 
26
32
  # automatic collections in the product's store that it now matches
27
- Spree::Collection.automatic.where(store_id: product.store_id).includes(:rules, :products).each do |collection|
33
+ Spree::Collection.automatic.where(store_id: product.store_id).includes(:rules, :products).find_each do |collection|
28
34
  collections_to_add << collection if collection.products.exclude?(product) && collection.products_matching_rules.ids.include?(product.id)
29
35
  end
30
36
 
@@ -56,11 +62,21 @@ module Spree
56
62
  Spree::Product.reset_counters(product.id, :product_collections)
57
63
  end
58
64
 
65
+ publish_membership_events(product, removed_rows, collections_to_add)
66
+
59
67
  success(product)
60
68
  end
61
69
 
62
70
  private
63
71
 
72
+ def publish_membership_events(product, removed_rows, added_collections)
73
+ removed_rows.each { |row| row.publish_event('product_collection.deleted') }
74
+ return if added_collections.empty?
75
+
76
+ Spree::ProductCollection.where(collection_id: added_collections.map(&:id), product_id: product.id).
77
+ find_each { |row| row.publish_event('product_collection.created') }
78
+ end
79
+
64
80
  def product_collection_attributes(collection, product, position)
65
81
  {
66
82
  collection_id: collection.id,
@@ -139,16 +139,19 @@ module Spree
139
139
  )
140
140
  end
141
141
 
142
+ # Handoff to a draft clears the cart reference. A SQL inequality alone
143
+ # drops those holds instead of counting them against competing checkouts.
142
144
  def held_by_others(stock_level_ids, owner)
143
145
  return {} if stock_level_ids.empty?
144
146
 
145
147
  owner_column = owner.is_a?(Spree::Cart) ? :cart_id : :order_id
146
- Spree::StockReservation
147
- .active
148
- .where(stock_level_id: stock_level_ids)
149
- .where.not(owner_column => owner.id)
150
- .group(:stock_level_id)
151
- .sum(:quantity)
148
+ owner_reference = Spree::StockReservation.arel_table[owner_column]
149
+ Spree::StockReservation.
150
+ active.
151
+ where(stock_level_id: stock_level_ids).
152
+ where(owner_reference.eq(nil).or(owner_reference.not_eq(owner.id))).
153
+ group(:stock_level_id).
154
+ sum(:quantity)
152
155
  end
153
156
 
154
157
  # One SELECT for all (stock_level_id, line_item_id) pairs we need to
@@ -57,8 +57,16 @@ module Spree
57
57
  apply_store_credits(remaining_total, except: payments.map(&:source_id)) if remaining_total.positive?
58
58
  end
59
59
 
60
+ # Allocates credit through an active payment method owned by the order store.
61
+ # No method is required when the outstanding amount is zero or negative.
62
+ #
63
+ # @param remaining_total [Numeric] maximum outstanding amount to allocate
64
+ # @param except [Array<Integer>] credit IDs already applied to this order
65
+ # @return [void]
60
66
  def apply_store_credits(remaining_total, except: [])
61
- payment_method = Spree::PaymentMethod::StoreCredit.available.first
67
+ return unless remaining_total.positive?
68
+
69
+ payment_method = @order.store.payment_methods.store_credit.available.first
62
70
  raise 'Store credit payment method could not be found' unless payment_method
63
71
 
64
72
  spendable_store_credits.where.not(id: except).oldest_first.each do |credit|
@@ -21,17 +21,6 @@ module Spree
21
21
  # The read timeout applies to each read, not the whole response, so a
22
22
  # slowly trickling answer needs an overall deadline as well.
23
23
  TOTAL_TIMEOUT = 2
24
- # Order-of-magnitude buckets: enough to tell a hobby install from a large
25
- # merchant, never an exact figure.
26
- BUCKETS = {
27
- 0..0 => '0',
28
- 1..9 => '1-9',
29
- 10..99 => '10-99',
30
- 100..999 => '100-999',
31
- 1_000..9_999 => '1k-9k',
32
- 10_000..99_999 => '10k-99k'
33
- }.freeze
34
- LARGEST_BUCKET = '100k+'.freeze
35
24
 
36
25
  class << self
37
26
  # Always false in the test environment and on CI servers (which set
@@ -77,13 +66,13 @@ module Spree
77
66
  install_id: Spree.install_id,
78
67
  ruby: RUBY_VERSION,
79
68
  rails: Rails.version,
80
- database: ActiveRecord::Base.connection_db_config.adapter,
81
- gems: Gem.loaded_specs.keys.grep(/\Aspree_/).sort.join(','),
82
- dashboard: dashboard_served?,
83
- stores: bucket(Spree::Store.count),
84
- products: bucket(Spree::Product.count),
85
- orders: bucket(Spree::Order.complete.count),
86
- sellers: seller_bucket
69
+ database: Diagnostics::Stack.database,
70
+ gems: Diagnostics::Stack.spree_gems.keys.join(','),
71
+ dashboard: Diagnostics::Stack.dashboard_served?,
72
+ stores: Diagnostics::Stack.bucket(Spree::Store.count),
73
+ products: Diagnostics::Stack.bucket(Spree::Product.count),
74
+ orders: Diagnostics::Stack.bucket(Spree::Order.complete.count),
75
+ sellers: Diagnostics::Stack.seller_bucket
87
76
  }.compact
88
77
  end
89
78
 
@@ -142,19 +131,6 @@ module Spree
142
131
  nil
143
132
  end
144
133
 
145
- def bucket(count)
146
- BUCKETS.find { |range, _| range.cover?(count) }&.last || LARGEST_BUCKET
147
- end
148
-
149
- def seller_bucket
150
- count = Spree::Seller.count
151
- bucket(count) if count.positive?
152
- end
153
-
154
- def dashboard_served?
155
- (defined?(Spree::Dashboard) && Spree::Dashboard.dist_path.present?) || Spree::Config.dashboard_url.present?
156
- end
157
-
158
134
  def env_flag?(name)
159
135
  ActiveModel::Type::Boolean.new.cast(ENV[name].presence) == true
160
136
  end