spree_core 6.0.3 → 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 (63) hide show
  1. checksums.yaml +4 -4
  2. data/app/jobs/spree/payments/handle_webhook_job.rb +12 -1
  3. data/app/models/concerns/spree/has_custom_fields.rb +4 -1
  4. data/app/models/concerns/spree/personal_data_matching.rb +5 -1
  5. data/app/models/concerns/spree/product_scopes.rb +2 -2
  6. data/app/models/concerns/spree/publishable.rb +26 -3
  7. data/app/models/spree/authentication/strategies/base_strategy.rb +10 -1
  8. data/app/models/spree/cart.rb +7 -2
  9. data/app/models/spree/invitation.rb +6 -2
  10. data/app/models/spree/media.rb +25 -1
  11. data/app/models/spree/order.rb +5 -1
  12. data/app/models/spree/price.rb +3 -0
  13. data/app/models/spree/product.rb +6 -9
  14. data/app/models/spree/product_category.rb +7 -1
  15. data/app/models/spree/product_collection.rb +8 -1
  16. data/app/models/spree/seller.rb +93 -10
  17. data/app/models/spree/seller_requirements/complete_profile.rb +26 -7
  18. data/app/models/spree/stock_level.rb +30 -1
  19. data/app/models/spree/stock_movement.rb +1 -0
  20. data/app/services/spree/carts/destroy.rb +22 -6
  21. data/app/services/spree/collections/regenerate_products.rb +37 -15
  22. data/app/services/spree/companies/add_member.rb +9 -4
  23. data/app/services/spree/diagnostics/error_log.rb +139 -0
  24. data/app/services/spree/diagnostics/section.rb +72 -0
  25. data/app/services/spree/diagnostics/sections.rb +121 -0
  26. data/app/services/spree/diagnostics/stack.rb +73 -0
  27. data/app/services/spree/diagnostics.rb +132 -0
  28. data/app/services/spree/newsletter/subscribe.rb +7 -3
  29. data/app/services/spree/orders/remove_line_item.rb +16 -5
  30. data/app/services/spree/product_memberships.rb +21 -1
  31. data/app/services/spree/product_types/apply_to_products.rb +12 -2
  32. data/app/services/spree/products/auto_match_collections.rb +20 -4
  33. data/app/services/spree/stock_reservations/reserve.rb +9 -6
  34. data/app/services/spree/store_credits/apply.rb +9 -1
  35. data/app/services/spree/update_check.rb +7 -31
  36. data/app/tools/spree/agent_tools/describe_resource.rb +3 -0
  37. data/app/tools/spree/agent_tools/get_resource.rb +1 -1
  38. data/app/tools/spree/agent_tools/resource_write.rb +1 -1
  39. data/app/tools/spree/agent_tools/search_resources.rb +42 -10
  40. data/app/workflows/spree/carts/add_item.rb +51 -0
  41. data/app/workflows/spree/carts/complete.rb +14 -2
  42. data/app/workflows/spree/payments/handle_webhook.rb +7 -3
  43. data/app/workflows/spree/sellers/approve.rb +6 -0
  44. data/app/workflows/spree/sellers/create.rb +5 -2
  45. data/app/workflows/spree/stock_levels/bulk_upsert.rb +19 -7
  46. data/config/locales/be.yml +1 -1
  47. data/config/locales/en.yml +8 -0
  48. data/config/locales/fr.yml +1 -1
  49. data/config/locales/lt.yml +1 -1
  50. data/config/locales/ru.yml +1 -1
  51. data/config/locales/uk.yml +1 -1
  52. data/db/migrate/20240303174340_fix_spree_stock_item_unique_index.rb +14 -10
  53. data/db/migrate/20260814000001_rename_stock_items_to_stock_levels.rb +13 -7
  54. data/lib/spree/agent_tool.rb +3 -3
  55. data/lib/spree/agent_tools/operation_tool.rb +1 -1
  56. data/lib/spree/agent_tools/record_summary.rb +8 -2
  57. data/lib/spree/agent_tools/resource_map.rb +82 -7
  58. data/lib/spree/core/engine.rb +10 -0
  59. data/lib/spree/core/version.rb +1 -1
  60. data/lib/spree/core.rb +11 -0
  61. data/lib/spree/reporting/default_vocabulary.rb +25 -5
  62. data/lib/tasks/diagnostics.rake +11 -0
  63. metadata +10 -4
@@ -12,24 +12,36 @@ module Spree
12
12
  return if collection.destroyed?
13
13
  return if collection.manual?
14
14
 
15
- previous_products_ids = collection.product_collections.order(position: :asc).pluck(:product_id)
15
+ # Loaded rather than plucked: a row dropped below is gone by the time
16
+ # its deleted event can be published, so it has to be held.
17
+ previous_rows = collection.product_collections.order(position: :asc).to_a
18
+ previous_products_ids = previous_rows.map(&:product_id)
19
+ matching_ids = collection.products_matching_rules.ids
20
+ matching = matching_ids.to_set
16
21
 
17
- # Hard-delete the join rows (no callbacks). Class-level delete on the collection
18
- # scope rather than the association proxy, which under `dependent: :destroy_async`
19
- # doesn't reliably remove rows here.
20
- Spree::ProductCollection.where(collection_id: collection.id).delete_all
22
+ retained_rows = previous_rows.select { |row| matching.include?(row.product_id) }
23
+ removed_rows = previous_rows - retained_rows
24
+ added_ids = matching_ids - previous_products_ids
21
25
 
22
- products_matching_rules = collection.products_matching_rules
23
- product_ids_to_insert = products_matching_rules.ids
26
+ # Hard-delete (no callbacks). Class-level delete rather than the
27
+ # association proxy, which under `dependent: :destroy_async` doesn't
28
+ # reliably remove rows here.
29
+ Spree::ProductCollection.where(id: removed_rows.map(&:id)).delete_all if removed_rows.any?
24
30
 
25
- previous_filtered_products_ids = previous_products_ids & product_ids_to_insert
26
- max_products_position = previous_filtered_products_ids.size || 0
31
+ # Close the gaps the removals left, keeping the survivors in the order
32
+ # they were already in. One statement rather than one per row:
33
+ # dropping an early member shifts every row behind it.
34
+ moved = retained_rows.each_with_index.filter_map do |row, index|
35
+ next if row.position == index + 1
27
36
 
28
- if product_ids_to_insert.any?
29
- records_to_insert = product_ids_to_insert.map do |product_id|
30
- position = previous_filtered_products_ids.index(product_id)
31
- position = position.present? ? position + 1 : max_products_position += 1
37
+ { id: row.id, collection_id: collection.id, product_id: row.product_id,
38
+ position: index + 1, created_at: row.created_at, updated_at: Time.current }
39
+ end
40
+
41
+ Spree::ProductCollection.upsert_all(moved, unique_by: (:id unless Spree.mysql?)) if moved.any?
32
42
 
43
+ if added_ids.any?
44
+ records_to_insert = added_ids.map.with_index(retained_rows.size + 1) do |product_id, position|
33
45
  product_collection_attributes(product_id, collection, position)
34
46
  end
35
47
 
@@ -38,19 +50,29 @@ module Spree
38
50
 
39
51
  # Expire cache + reindex the union of previous and new members, so products
40
52
  # dropped when the match set empties also refresh their stale collection_ids.
41
- products = Spree::Product.where(id: (previous_products_ids + product_ids_to_insert).uniq)
53
+ products = Spree::Product.where(id: (previous_products_ids + matching_ids).uniq)
42
54
  products.touch_all
43
55
  products.each(&:enqueue_search_index)
44
56
 
45
57
  # counter caches — bulk insert/delete bypass the ProductCollection counter_cache callbacks
46
58
  Spree::Collection.reset_counters(collection.id, :product_collections)
47
- Spree::Product.reset_counters_in_bulk(previous_products_ids + product_ids_to_insert, :product_collections)
59
+ Spree::Product.reset_counters_in_bulk(previous_products_ids + matching_ids, :product_collections)
60
+
61
+ publish_membership_events(collection, removed_rows, added_ids)
48
62
 
49
63
  success(collection)
50
64
  end
51
65
 
52
66
  private
53
67
 
68
+ def publish_membership_events(collection, removed_rows, added_ids)
69
+ removed_rows.each { |row| row.publish_event('product_collection.deleted') }
70
+ return if added_ids.empty?
71
+
72
+ Spree::ProductCollection.where(collection_id: collection.id, product_id: added_ids).
73
+ find_each { |row| row.publish_event('product_collection.created') }
74
+ end
75
+
54
76
  def product_collection_attributes(product_id, collection, position)
55
77
  {
56
78
  product_id: product_id,
@@ -11,7 +11,10 @@ module Spree
11
11
  prepend Spree::ServiceModule::Base
12
12
 
13
13
  # @param company [Spree::Company]
14
- # @param email [String]
14
+ # @param email [String, nil] who to add, when no +customer+ is given
15
+ # @param customer [Spree.customer_class, nil] an existing customer, who
16
+ # becomes a member immediately — for a caller that picked them rather
17
+ # than typed an address
15
18
  # @param inviter [Object, nil] the inviting customer, nil when staff
16
19
  # @param metadata [Hash, nil] extension payload — carried on the
17
20
  # invitation only, where Enterprise reads it back on acceptance
@@ -26,9 +29,11 @@ module Spree
26
29
  # whoever happens to hold that email.
27
30
  # @return [Spree::ServiceModule::Result] value is the created
28
31
  # Spree::CompanyMembership or Spree::CompanyInvitation
29
- def call(company:, email:, inviter: nil, metadata: nil, require_acceptance: false)
30
- normalized_email = email.to_s.strip.downcase
31
- customer = Spree.customer_class.find_by(email: normalized_email) unless require_acceptance
32
+ def call(company:, email: nil, customer: nil, inviter: nil, metadata: nil, require_acceptance: false)
33
+ normalized_email = (email.presence || customer&.email).to_s.strip.downcase
34
+ # Acceptance outranks a customer handed in: they are invited by their
35
+ # address like anyone else, so only the holder can agree to join.
36
+ customer = require_acceptance ? nil : (customer || Spree.customer_class.find_by(email: normalized_email))
32
37
 
33
38
  record =
34
39
  if customer
@@ -0,0 +1,139 @@
1
+ module Spree
2
+ class Diagnostics
3
+ # The most recent Spree errors, for the diagnostics report. Subscribed to
4
+ # the Rails error reporter, so it sees what Spree reports with
5
+ # +Rails.error.report+ as well as unhandled request and job errors.
6
+ #
7
+ # Only the exception class and where it was raised are kept, never the
8
+ # message: messages carry customer data (emails, addresses, values echoed
9
+ # from a row) and the report ends up in a public issue. Frames from the
10
+ # host application become +app/[redacted]+ and frames from private gems
11
+ # +gem/[redacted]+, so the merchant's own code is not shared either.
12
+ #
13
+ # Entries live in Rails.cache, so a cache clear empties the log. With a
14
+ # per-process memory store a restart does too, and each process keeps its
15
+ # own.
16
+ class ErrorLog
17
+ CACHE_KEY = 'spree/diagnostics/errors'.freeze
18
+ LIMIT = 50
19
+ FRAME_LIMIT = 10
20
+ HOST_FRAME = 'app/[redacted]'.freeze
21
+ PRIVATE_FRAME = 'gem/[redacted]'.freeze
22
+ RECORDING = :spree_diagnostics_error_log_recording
23
+
24
+ # One backtrace line, as the report shows it.
25
+ Frame = Struct.new(:text, :spree, :host)
26
+
27
+ class << self
28
+ # @return [Array<Hash>] newest first
29
+ def entries
30
+ Array(Rails.cache.read(CACHE_KEY)).sort_by { |entry| entry[:last_seen_at] }.reverse
31
+ end
32
+
33
+ # @return [void]
34
+ def clear
35
+ Rails.cache.delete(CACHE_KEY)
36
+ end
37
+
38
+ # Gem directories and the application's, longest first, so a path is
39
+ # matched by the most specific root: a gem vendored inside the app is
40
+ # that gem, and an app inside a gem's directory (a test dummy app) is
41
+ # the app. Built once per process, since every reported error needs it.
42
+ #
43
+ # @return [Array<Array(String, Proc)>] path prefix and the frame it makes
44
+ def roots
45
+ @roots ||= Gem.loaded_specs.values.map { |spec| [spec.full_gem_path + File::SEPARATOR, gem_frame(spec)] }.
46
+ push([Rails.root.to_s + File::SEPARATOR, ->(_) { Frame.new(HOST_FRAME, false, true) }]).
47
+ sort_by { |root, _| -root.length }
48
+ end
49
+
50
+ private
51
+
52
+ def gem_frame(spec)
53
+ return ->(_) { Frame.new(PRIVATE_FRAME, false, false) } unless Stack.public_gem?(spec)
54
+
55
+ spree = Stack.spree_gem?(spec)
56
+ ->(relative) { Frame.new("#{spec.name}-#{spec.version}/#{relative}", spree, false) }
57
+ end
58
+ end
59
+
60
+ # Rails error subscriber interface. Leaves out refused requests: an
61
+ # error Rails answers with a 4xx (an invalid record, a missing one, a
62
+ # bad parameter) is the client's, not a bug. Never raises, and never
63
+ # recurses: a cache store that reports its own failure to Rails.error
64
+ # would otherwise call back in here.
65
+ def report(error, context:, source: nil, **)
66
+ return if Thread.current[RECORDING] || client_error?(error)
67
+
68
+ recording do
69
+ frames = frames_for(error)
70
+ record(error.class.name, source, frames, request_id(context)) if spree_error?(source, frames)
71
+ end
72
+ rescue StandardError
73
+ nil
74
+ end
75
+
76
+ private
77
+
78
+ # Only the outermost call clears the flag: a nested call that returned
79
+ # early would otherwise re-arm recursion for the rest of the outer one.
80
+ def recording
81
+ Thread.current[RECORDING] = true
82
+ yield
83
+ ensure
84
+ Thread.current[RECORDING] = nil
85
+ end
86
+
87
+ def record(error_class, source, frames, request_id)
88
+ now = Time.current.iso8601
89
+ fingerprint = [error_class, (frames.find(&:spree) || frames.first)&.text].join('|')
90
+ entries = Array(Rails.cache.read(CACHE_KEY))
91
+ entry = entries.find { |existing| existing[:fingerprint] == fingerprint }
92
+
93
+ if entry
94
+ entry.merge!(count: entry[:count] + 1, last_seen_at: now, request_id: request_id || entry[:request_id])
95
+ else
96
+ entries << { fingerprint: fingerprint, error_class: error_class, source: source, frames: frames.map(&:text),
97
+ request_id: request_id, count: 1, first_seen_at: now, last_seen_at: now }
98
+ end
99
+
100
+ kept = entries.sort_by { |existing| existing[:last_seen_at] }.last(LIMIT)
101
+ Rails.cache.write(CACHE_KEY, kept)
102
+ end
103
+
104
+ # Spree's when Spree reported it, or when Spree code ran between the
105
+ # raise and the host application. Every request also passes through
106
+ # Spree's middleware further out, so frames past the first host
107
+ # application frame don't count: an error raised in the merchant's own
108
+ # controller is theirs.
109
+ def spree_error?(source, frames)
110
+ source.to_s.start_with?('spree') || frames.take_while { |frame| !frame.host }.any?(&:spree)
111
+ end
112
+
113
+ # Where the error was raised, then every Spree frame and the host
114
+ # application's (collapsed), so the Spree line that led to a library
115
+ # error isn't pushed out by the library's own frames. Ruby's own frames
116
+ # are dropped.
117
+ def frames_for(error)
118
+ origin, *rest = Array(error.backtrace).filter_map { |line| frame(line) }
119
+ [origin, *rest.select { |frame| frame.spree || frame.host }].compact.
120
+ chunk_while { |a, b| a.host && b.host }.map(&:first).first(FRAME_LIMIT)
121
+ end
122
+
123
+ def frame(line)
124
+ path = line.sub(/:in .*\z/, '')
125
+ root, make = self.class.roots.find { |prefix, _| path.start_with?(prefix) }
126
+ make&.call(path.delete_prefix(root))
127
+ end
128
+
129
+ def client_error?(error)
130
+ ActionDispatch::ExceptionWrapper.status_code_for_exception(error.class.name) < 500
131
+ end
132
+
133
+ def request_id(context)
134
+ controller = context[:controller]
135
+ context[:request_id] || (controller.request.request_id if controller.respond_to?(:request))
136
+ end
137
+ end
138
+ end
139
+ end
@@ -0,0 +1,72 @@
1
+ module Spree
2
+ class Diagnostics
3
+ # One part of the diagnostics report. A subclass names its rows; each row
4
+ # is read separately and reports "unavailable" when reading it fails, since
5
+ # a half-broken installation is exactly when the report is needed.
6
+ #
7
+ # Everything a row returns ends up in a public GitHub issue, so a row adds
8
+ # one deliberately chosen fact: never a name, URL, email or credential, and
9
+ # records only by prefixed ID.
10
+ #
11
+ # class MyGem::DiagnosticsSection < Spree::Diagnostics::Section
12
+ # def title = 'My gem'
13
+ #
14
+ # def rows
15
+ # { 'Mode' => -> { MyGem.config.mode } }
16
+ # end
17
+ # end
18
+ #
19
+ # Spree.diagnostics_sections << 'MyGem::DiagnosticsSection'
20
+ class Section
21
+ UNAVAILABLE = 'unavailable'.freeze
22
+
23
+ attr_reader :store
24
+
25
+ # @param store [Spree::Store]
26
+ def initialize(store)
27
+ @store = store
28
+ end
29
+
30
+ # @return [String]
31
+ def key
32
+ self.class.name.demodulize.underscore
33
+ end
34
+
35
+ # @return [String]
36
+ def title
37
+ raise NotImplementedError
38
+ end
39
+
40
+ # @return [Hash{String => Proc}] label => reader
41
+ def rows
42
+ raise NotImplementedError
43
+ end
44
+
45
+ # @return [Array<Hash>] `{ label:, value: }`, values as strings
46
+ def to_rows
47
+ rows.filter_map do |label, reader|
48
+ value = read(reader)
49
+ { label: label, value: value } unless value.nil?
50
+ end
51
+ end
52
+
53
+ private
54
+
55
+ def read(reader)
56
+ format_value(reader.call)
57
+ rescue StandardError
58
+ UNAVAILABLE
59
+ end
60
+
61
+ def format_value(value)
62
+ case value
63
+ when nil then nil
64
+ when true then 'yes'
65
+ when false then 'no'
66
+ when Array then value.compact_blank.join(', ').presence || 'none'
67
+ else value.to_s
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
@@ -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
@@ -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