spree_core 6.0.1 → 6.0.3

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 (85) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +2 -2
  3. data/app/jobs/spree/addresses/geocode_address_job.rb +6 -3
  4. data/app/jobs/spree/variants/remove_line_item_job.rb +5 -0
  5. data/app/models/concerns/spree/admin_user_methods.rb +23 -0
  6. data/app/models/concerns/spree/preference_schema.rb +5 -0
  7. data/app/models/concerns/spree/typed_associations.rb +53 -20
  8. data/app/models/concerns/spree/user_roles.rb +9 -4
  9. data/app/models/spree/address.rb +2 -2
  10. data/app/models/spree/collection.rb +7 -2
  11. data/app/models/spree/order.rb +4 -2
  12. data/app/models/spree/order_promotion.rb +3 -1
  13. data/app/models/spree/payment.rb +16 -1
  14. data/app/models/spree/payment_method/store_credit.rb +3 -1
  15. data/app/models/spree/payment_method.rb +14 -1
  16. data/app/models/spree/payment_source.rb +3 -1
  17. data/app/models/spree/product.rb +15 -5
  18. data/app/models/spree/promotion/actions/create_item_adjustments.rb +1 -1
  19. data/app/models/spree/promotion.rb +11 -3
  20. data/app/models/spree/promotion_handler/cart.rb +7 -1
  21. data/app/models/spree/promotion_handler/coupon.rb +1 -29
  22. data/app/models/spree/refresh_token.rb +26 -0
  23. data/app/models/spree/variant.rb +1 -1
  24. data/app/services/spree/newsletter/subscribe.rb +1 -1
  25. data/app/services/spree/orders/create_from_cart.rb +6 -2
  26. data/app/services/spree/promotions/detach_from_owner.rb +72 -0
  27. data/app/services/spree/stock_reservations/reserve.rb +6 -2
  28. data/app/tools/spree/agent_tools/create_export.rb +3 -1
  29. data/app/tools/spree/agent_tools/create_import.rb +1 -0
  30. data/app/tools/spree/agent_tools/create_media.rb +2 -1
  31. data/app/tools/spree/agent_tools/create_resource.rb +12 -4
  32. data/app/tools/spree/agent_tools/delete_resource.rb +12 -4
  33. data/app/tools/spree/agent_tools/describe_resource.rb +69 -6
  34. data/app/tools/spree/agent_tools/get_resource.rb +7 -4
  35. data/app/tools/spree/agent_tools/resource_write.rb +15 -2
  36. data/app/tools/spree/agent_tools/search_resources.rb +10 -11
  37. data/app/tools/spree/agent_tools/update_resource.rb +6 -6
  38. data/app/tools/spree/agent_tools/upload_file.rb +1 -0
  39. data/app/workflows/spree/carts/complete.rb +4 -1
  40. data/app/workflows/spree/carts/merge.rb +25 -4
  41. data/app/workflows/spree/carts/recalculate.rb +5 -1
  42. data/app/workflows/spree/orders/complete.rb +39 -14
  43. data/app/workflows/spree/products/activate.rb +7 -2
  44. data/app/workflows/spree/products/archive.rb +7 -2
  45. data/app/workflows/spree/products/draft.rb +7 -2
  46. data/app/workflows/spree/products/status_transition.rb +24 -0
  47. data/config/locales/en.yml +3 -0
  48. data/db/migrate/20260809150001_promote_shipping_categories_to_delivery_profiles.rb +15 -6
  49. data/db/migrate/20261030100001_scope_payment_sources_profile_id_uniqueness_to_payment_method.rb +38 -0
  50. data/db/migrate/20261031000001_add_last_active_at_to_spree_admin_users.rb +7 -0
  51. data/db/migrate/20261031100001_delete_orphaned_spree_option_value_variants.rb +10 -0
  52. data/lib/generators/spree/api_resource/api_resource_generator.rb +35 -3
  53. data/lib/generators/spree/api_resource/templates/admin_controller.rb.tt +9 -4
  54. data/lib/generators/spree/api_resource/templates/admin_integration_spec.rb.tt +74 -0
  55. data/lib/generators/spree/api_resource/templates/store_controller.rb.tt +11 -6
  56. data/lib/generators/spree/dummy/dummy_generator.rb +0 -1
  57. data/lib/generators/spree/dummy/templates/rails/database.yml +6 -9
  58. data/lib/generators/spree/dummy/templates/rails/test.rb +9 -5
  59. data/lib/generators/spree/dummy_model/templates/migration.rb.tt +1 -1
  60. data/lib/spree/agent_tool.rb +105 -1
  61. data/lib/spree/agent_tools/default_catalog.rb +16 -21
  62. data/lib/spree/agent_tools/legacy_tools.rb +212 -0
  63. data/lib/spree/agent_tools/operation_catalog.rb +206 -0
  64. data/lib/spree/agent_tools/operation_tool.rb +189 -0
  65. data/lib/spree/agent_tools/registry.rb +65 -31
  66. data/lib/spree/agent_tools/resource_map.rb +128 -5
  67. data/lib/spree/agent_tools.rb +3 -3
  68. data/lib/spree/core/dependencies_helper.rb +96 -40
  69. data/lib/spree/core/engine.rb +2 -1
  70. data/lib/spree/core/version.rb +1 -1
  71. data/lib/spree/core.rb +19 -5
  72. data/lib/spree/testing_support/common_rake.rb +3 -2
  73. data/lib/spree/testing_support/extension_rake.rb +12 -0
  74. data/lib/spree/testing_support/lifecycle_events.rb +1 -3
  75. data/lib/spree/upgrades/5_6_to_6_0/manifest.yml +36 -1
  76. data/lib/tasks/delivery_migration.rake +17 -1
  77. data/lib/tasks/dependencies.rake +2 -2
  78. data/lib/tasks/remove_orphan_order_promotions.rake +20 -0
  79. metadata +19 -69
  80. data/lib/generators/spree/authentication/dummy/dummy_generator.rb +0 -54
  81. data/lib/generators/spree/authentication/dummy/templates/authentication_helpers.rb.tt +0 -52
  82. data/lib/generators/spree/authentication/dummy/templates/create_spree_admin_users.rb.tt +0 -33
  83. data/lib/spree/agent_tools/workflow_endpoints.rb +0 -88
  84. data/lib/spree/agent_tools/workflow_schema.rb +0 -279
  85. data/lib/spree/agent_tools/workflow_tool.rb +0 -654
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2407d5fb2d24d9dd893a8c9dae11cfd8aba5a4b1d621a82938a2cb7009581936
4
- data.tar.gz: f3384773e3442f383e979f60d58b7b06672a72065cd8d117a114ef49827fda5e
3
+ metadata.gz: a2157ca6ce976c9676d3c814939c6a69e8fd835b8864d73006b274f1216f2d4e
4
+ data.tar.gz: 8a80c4a0d322fafe8ff3f4accb3bf293bfca4f4cf341a98015e8a494c0373185
5
5
  SHA512:
6
- metadata.gz: ebc83d9db9ebc13afea53ae0b184789f32a81121dcd9608461d93fb7e2e62b020cef774e69de3404fc0d23adb62df13f770281eacd6fd4671e5c0f5328ecae5b
7
- data.tar.gz: 99ecc2439e9a73c1f805898c35e48079cd573b947110951c1a8349b26934e7ea8023b55a53cfdf1b3af94a5013290c52e5a097e4e5dff61d1249af8ca3327fb7
6
+ metadata.gz: 290b7d040a689ce9be4d01e20713ca97476d8b2b5ab1e8e735fad6bf651103375f037e2f96bb767662b866069d6c01219eae6d5d8da1de2ffed3a1e01756ab25
7
+ data.tar.gz: bd9a079e8712771a6a77453e9ae63bdf6a75a39d549c3db86eb326a5f7ab60896e6ff2196274380d5805f583487b43a24f0c198feb780ab40bddf11c1b0e26bb
data/README.md CHANGED
@@ -110,6 +110,6 @@ bundle exec rspec
110
110
 
111
111
  ## Documentation
112
112
 
113
- - [Official Documentation](https://docs.spreecommerce.org)
113
+ - [Official Documentation](https://spreecommerce.org/docs)
114
114
  - [API Reference](https://api.spreecommerce.org)
115
- - [Guides](https://docs.spreecommerce.org/developer)
115
+ - [Guides](https://spreecommerce.org/docs/developer)
@@ -16,11 +16,14 @@ module Spree
16
16
  if coordinates.present?
17
17
  address.update_columns(latitude: coordinates[0], longitude: coordinates[1], updated_at: Time.current)
18
18
  else
19
- # Unfortunately there is no way to get the error message from Geocoder,
20
- # but the request is fully displayed in the server logs
19
+ # An address the geocoder cannot resolve is a data problem rather than
20
+ # a bug, so it is reported as a handled warning. Unfortunately there is
21
+ # no way to get the error message from Geocoder, but the request is
22
+ # fully displayed in the server logs
21
23
  Rails.error.report(
22
24
  GeocodeAddressError.new("Cannot geocode address ID: #{address.id}"),
23
- handled: false,
25
+ handled: true,
26
+ severity: :warning,
24
27
  context: { address_id: address_id },
25
28
  source: 'spree.core'
26
29
  )
@@ -7,6 +7,11 @@ module Spree
7
7
  owner = line_item.owner
8
8
  return if owner.nil?
9
9
 
10
+ # A completed cart is a read-only audit record; the order it became
11
+ # owns the lines now. The cart can complete between this job being
12
+ # enqueued and running, and there is nothing left to remove from it.
13
+ return if owner.is_a?(Spree::Cart) && owner.readonly?
14
+
10
15
  # Carts and draft orders have different contracts: the cart side turns
11
16
  # a vetoed removal into a warning and still succeeds, the order side
12
17
  # fails outright. Routing an order-owned line through the cart
@@ -2,6 +2,8 @@ module Spree
2
2
  module AdminUserMethods
3
3
  extend ActiveSupport::Concern
4
4
 
5
+ STATUSES = %w[active locked deactivated].freeze
6
+
5
7
  include Spree::Actor
6
8
  include Spree::PrefixedId
7
9
  include Spree::SignedIdAttachments
@@ -43,6 +45,8 @@ module Spree
43
45
 
44
46
  # Associations
45
47
  has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroy
48
+ # Signed-in sessions, on the admin and the seller API alike.
49
+ has_many :refresh_tokens, class_name: 'Spree::RefreshToken', as: :user, dependent: :delete_all
46
50
  # The order operations became polymorphic in 6.0, so these read through
47
51
  # the association rather than a bare foreign key: matching on the id
48
52
  # alone would hand this user the rows an API key with the same numeric
@@ -84,6 +88,25 @@ module Spree
84
88
  Spree::Store.current.users.where.not(id: id).exists?
85
89
  end
86
90
 
91
+ # Whether the account can sign in. Duck-typed: a custom admin user class
92
+ # may lack deactivation or lockout.
93
+ # @return [String] +active+, +locked+ or +deactivated+
94
+ def status
95
+ if try(:deactivated?)
96
+ 'deactivated'
97
+ elsif try(:locked?)
98
+ 'locked'
99
+ else
100
+ 'active'
101
+ end
102
+ end
103
+
104
+ # Sessions that can still be refreshed, most recently used first.
105
+ # @return [ActiveRecord::Relation<Spree::RefreshToken>]
106
+ def active_sessions
107
+ refresh_tokens.active.order(created_at: :desc)
108
+ end
109
+
87
110
  # Returns the full name of the user
88
111
  # @return [String]
89
112
  def full_name
@@ -217,6 +217,11 @@ module Spree
217
217
  registered_subclasses.find { |klass| klass.api_type == shorthand.to_s }
218
218
  end
219
219
 
220
+ # @return [Array<String>] the wire name of every registered subclass
221
+ def api_types
222
+ registered_subclasses.map(&:api_type)
223
+ end
224
+
220
225
  # Returns a `[{ type:, label:, description:, schema: }]` array for every
221
226
  # registered subclass, sorted by label for stable output. `schema` is
222
227
  # the JSON Schema of the subclass's `preferences`, which never carries a
@@ -37,37 +37,55 @@ module Spree
37
37
  reconcile_typed_association(association, pending)
38
38
  end
39
39
 
40
- # Flushes a pending payload from `@pending_<assoc>` (typically from
41
- # an `after_save` hook) and clears the ivar.
40
+ # Flushes the pending payloads from `@pending_<assoc>` (typically from
41
+ # an `after_save` hook) and clears them.
42
42
  #
43
+ # Every association is written before any buffer is cleared: a refused
44
+ # row rolls the whole save back, and a retried save must carry every
45
+ # payload again rather than persist the owner with the rows that
46
+ # happened to come first.
47
+ #
48
+ # @param associations [Array<Symbol>]
49
+ # @return [void]
50
+ def flush_pending_typed_associations(*associations)
51
+ pending = associations.to_h { |association| [association, instance_variable_get(:"@pending_#{association}")] }.compact
52
+ pending.each { |association, rows| reconcile_typed_association(association, rows) }
53
+ pending.each_key { |association| instance_variable_set(:"@pending_#{association}", nil) }
54
+ end
55
+
43
56
  # @param association [Symbol]
44
57
  # @return [void]
45
58
  def flush_pending_typed_association(association)
46
- ivar = :"@pending_#{association}"
47
- pending = instance_variable_get(ivar)
48
- return unless pending
49
-
50
- instance_variable_set(ivar, nil)
51
- reconcile_typed_association(association, pending)
59
+ flush_pending_typed_associations(association)
52
60
  end
53
61
 
62
+ # All or nothing: on a saved parent the rows are written as they are
63
+ # assigned, so a refusal on the second row used to leave the first one
64
+ # behind — a list the caller never asked for, answered with a 422.
54
65
  def reconcile_typed_association(association, rows)
55
66
  collection = public_send(association)
56
- kept_ids = rows.each_with_index.filter_map { |row, index| save_typed_association_row(collection, row, "/#{association.to_s.split('_').last}/#{index}") }
57
- if kept_ids.any? || rows.empty?
58
- collection.where.not(id: kept_ids).destroy_all
59
- # `where.not(...).destroy_all` deletes the dropped rows from the DB but
60
- # leaves them in the already-loaded association target. Reset so a
61
- # same-request read (e.g. the serializer rendering `rule_ids`) reflects
62
- # the removal instead of echoing ghosts.
67
+ begin
68
+ self.class.transaction do
69
+ kept_ids = rows.each_with_index.map { |row, index| save_typed_association_row(collection, row, "/#{association.to_s.split('_').last}/#{index}") }
70
+ collection.where.not(id: kept_ids).destroy_all
71
+ # `where.not(...).destroy_all` deletes the dropped rows from the DB but
72
+ # leaves them in the already-loaded association target. Reset so a
73
+ # same-request read (e.g. the serializer rendering `rule_ids`) reflects
74
+ # the removal instead of echoing ghosts.
75
+ collection.reset
76
+ end
77
+ rescue StandardError
78
+ # The rows built before the refusal are still in the loaded target, and
79
+ # the owner's next save would write them; the rollback only undid the
80
+ # database.
63
81
  collection.reset
82
+ raise
64
83
  end
65
84
  end
66
85
 
67
86
  # @param pointer [String] where the row sits in the request, e.g. `/rules/1`
68
87
  def save_typed_association_row(collection, row, pointer)
69
- record = find_or_build_typed_association_row(collection, row)
70
- return nil unless record
88
+ record = find_or_build_typed_association_row(collection, row, pointer)
71
89
 
72
90
  preferences = row[:preferences]
73
91
  calculator = row[:calculator]
@@ -100,15 +118,19 @@ module Spree
100
118
  raise
101
119
  end
102
120
 
103
- def find_or_build_typed_association_row(collection, row)
121
+ def find_or_build_typed_association_row(collection, row, pointer)
104
122
  if row[:id].present?
105
123
  id = Spree::PrefixedId.prefixed_id?(row[:id]) ? Spree::PrefixedId.decode_prefixed_id(row[:id]) : row[:id]
106
124
  existing = collection.find { |r| r.id == id } || collection.find_by(id: id)
107
125
  return existing if existing
108
126
  end
109
127
 
110
- klass = collection.proxy_association.klass.find_by_api_type(row[:type])
111
- return nil unless klass
128
+ family = collection.proxy_association.klass
129
+ klass = family.find_by_api_type(row[:type])
130
+ # Refused, not skipped: a dropped row answered the request with a 200
131
+ # and a promotion that discounted nothing. Naming the accepted types is
132
+ # what lets an API client or an agent correct itself.
133
+ raise unknown_row_type_error(family, row[:type], pointer) unless klass
112
134
 
113
135
  # `build(type:) + becomes(klass)` would leave a stale STI-parent stub
114
136
  # in the collection target alongside the becomes'd copy; autosave then
@@ -117,5 +139,16 @@ module Spree
117
139
  collection.proxy_association.add_to_target(record)
118
140
  record
119
141
  end
142
+
143
+ def unknown_row_type_error(family, type, pointer)
144
+ types = family.api_types.sort.join(', ')
145
+ message = if type.blank?
146
+ I18n.t('spree.errors.messages.missing_row_type', types: types)
147
+ else
148
+ I18n.t('spree.errors.messages.unknown_row_type', type: type, family: family.model_name.human.downcase, types: types)
149
+ end
150
+
151
+ Spree::Preferences::InvalidPreferences.new([{ pointer: '/type', message: message }], prefix: pointer)
152
+ end
120
153
  end
121
154
  end
@@ -57,10 +57,15 @@ module Spree
57
57
  has_spree_role?(Spree::Role::ADMIN_ROLE, resource)
58
58
  end
59
59
 
60
- # Returns the user who invited the current user
61
- # @return [Spree.admin_user_class]
62
- def invited_by
63
- invitations.first&.inviter
60
+ # Who sent the invitation this user accepted to get a role on +resource+.
61
+ # Nil for a user given a role without one, such as the store owner.
62
+ #
63
+ # @param resource [Spree::Base] the store or seller; defaults to the current store
64
+ # @return [Object, nil] an actor (see Spree.actor_classes)
65
+ def invited_by(resource = nil)
66
+ resource ||= Spree::Store.current
67
+
68
+ invitations.accepted.where(resource: resource).order(:created_at).first&.inviter
64
69
  end
65
70
 
66
71
  # Whether this user belongs to any marketplace seller. The seller login
@@ -270,10 +270,10 @@ module Spree
270
270
  #
271
271
  # @return [String, nil]
272
272
  def company
273
- stored = read_attribute(:company)
273
+ stored = super
274
274
  return stored if stored.present?
275
275
 
276
- owner.name if owner.is_a?(Spree::Company)
276
+ owner&.name if owner_type == 'Spree::Company'
277
277
  end
278
278
 
279
279
  # Whether the owner prefills with this address. Every owner keeps the
@@ -203,10 +203,15 @@ module Spree
203
203
  existing_by_id = rules.to_a.index_by(&:id)
204
204
  retained_ids = []
205
205
 
206
- rules_params.each do |rule_data|
206
+ rules_params.each_with_index do |rule_data, index|
207
207
  data = rule_data.to_h.with_indifferent_access
208
208
  rule_id = data.delete(:id)
209
- data[:type] = self.class.resolve_rule_type(data[:type]) if data.key?(:type)
209
+ if data.key?(:type) || rule_id.blank?
210
+ # Refused with the accepted kinds named; letting the nil through
211
+ # answered "type can't be blank" to a caller who had sent one.
212
+ data[:type] = self.class.resolve_rule_type(data[:type]) ||
213
+ raise(unknown_row_type_error(Spree::CollectionRule, data[:type], "/rules/#{index}"))
214
+ end
210
215
 
211
216
  record = if rule_id.present?
212
217
  existing_by_id[Spree::PrefixedId.decode_prefixed_id(rule_id) || rule_id] ||
@@ -337,8 +337,10 @@ module Spree
337
337
  scope :reverse_chronological, -> { order(Arel.sql('spree_orders.completed_at IS NULL'), completed_at: :desc, created_at: :desc) }
338
338
 
339
339
  def self.search(query)
340
+ # Ransack passes `true` when the scope is called as a bare flag (`q[search]=1`)
341
+ return none unless query.is_a?(String) && query.present?
342
+
340
343
  sanitized_query = sanitize_query_for_search(query)
341
- return none if query.blank?
342
344
 
343
345
  query_pattern = "%#{sanitized_query}%"
344
346
 
@@ -827,7 +829,7 @@ module Spree
827
829
  # reaches it through +Spree.carts_complete_workflow+). Removed in 6.1.
828
830
  def finalize!
829
831
  Spree::Deprecation.warn('Spree::Order#finalize! is deprecated and will be removed in Spree 6.1. Completion runs through Spree.order_complete_workflow (Spree::Orders::Complete).')
830
- Spree.order_complete_workflow.call(order: self, payment_pending: true)
832
+ Spree.order_complete_workflow.call(order: self, payment_pending: true, validated: true)
831
833
  end
832
834
 
833
835
  def fulfill!
@@ -8,7 +8,7 @@ module Spree
8
8
  belongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :order_promotions
9
9
  belongs_to :promotion, class_name: 'Spree::Promotion'
10
10
 
11
- delegate :name, :description, :code, to: :promotion
11
+ delegate :name, :description, :code, to: :promotion, allow_nil: true
12
12
  delegate :currency, to: :owner
13
13
 
14
14
  validates :order, uniqueness: { scope: :promotion }, allow_nil: true
@@ -35,6 +35,8 @@ module Spree
35
35
  end
36
36
 
37
37
  def amount
38
+ return BigDecimal(0) if promotion.nil?
39
+
38
40
  owner.discounts.promotion.where(promotion_action_id: promotion.actions.ids).sum(:amount)
39
41
  end
40
42
 
@@ -27,6 +27,11 @@ module Spree
27
27
  INVALID_STATES = INVALID_STATUSES
28
28
  deprecate_constant :INVALID_STATES
29
29
 
30
+ # Statuses a payment can be voided / captured from, before the payment
31
+ # method is consulted. Extend them to support gateways with other flows.
32
+ VOIDABLE_STATUSES = %w[pending processing completed checkout].freeze
33
+ CAPTURABLE_STATUSES = %w[checkout pending].freeze
34
+
30
35
  with_options inverse_of: :payments do
31
36
  belongs_to :order, class_name: 'Spree::Order', touch: true, optional: true
32
37
  belongs_to :cart, class_name: 'Spree::Cart', optional: true
@@ -219,8 +224,18 @@ module Spree
219
224
  status.in?(%w[checkout processing])
220
225
  end
221
226
 
227
+ # Whether the payment is in a status that can be voided and its payment
228
+ # method agrees. A gateway that cannot void a capture returns false from
229
+ # +can_void?(payment)+ for completed payments.
222
230
  def can_void?
223
- status.in?(%w[pending processing completed checkout])
231
+ status.in?(VOIDABLE_STATUSES) &&
232
+ (!payment_method.respond_to?(:can_void?) || payment_method.can_void?(self))
233
+ end
234
+
235
+ # Whether the payment can be captured from the back office.
236
+ def can_capture?
237
+ status.in?(CAPTURABLE_STATUSES) &&
238
+ (!payment_method.respond_to?(:can_capture?) || payment_method.can_capture?(self))
224
239
  end
225
240
 
226
241
  # @deprecated read +status+ — removed in 6.1
@@ -18,8 +18,10 @@ module Spree
18
18
  ['checkout', 'pending'].include?(payment.status)
19
19
  end
20
20
 
21
+ # Mirrors Spree::StoreCredit#can_void?: a checkout payment can still be
22
+ # voided while its order is incomplete.
21
23
  def can_void?(payment)
22
- payment.pending?
24
+ payment.pending? || (payment.checkout? && !payment.order&.completed?)
23
25
  end
24
26
 
25
27
  def authorize(money, store_credit, gateway_options = {})
@@ -197,7 +197,7 @@ module Spree
197
197
  def webhook_url
198
198
  return nil unless store
199
199
 
200
- "#{store.url_or_custom_domain}/api/v3/webhooks/payments/#{prefixed_id}"
200
+ "#{store.formatted_url_or_custom_domain}/api/v3/webhooks/payments/#{prefixed_id}"
201
201
  end
202
202
 
203
203
  class WebhookSignatureError < StandardError; end
@@ -309,6 +309,19 @@ module Spree
309
309
  raise ::NotImplementedError, 'You must implement cancel method for this payment method.'
310
310
  end
311
311
 
312
+ # Whether the payment can be voided in its current state. Gateways that
313
+ # cannot void a captured payment override this.
314
+ # @param _payment [Spree::Payment]
315
+ def can_void?(_payment)
316
+ true
317
+ end
318
+
319
+ # Whether the payment can be captured in its current state.
320
+ # @param _payment [Spree::Payment]
321
+ def can_capture?(_payment)
322
+ true
323
+ end
324
+
312
325
  def store_credit?
313
326
  self.class == Spree::PaymentMethod::StoreCredit
314
327
  end
@@ -17,7 +17,9 @@ module Spree
17
17
  #
18
18
  # Validations
19
19
  #
20
- validates_uniqueness_of :gateway_payment_profile_id, scope: :type
20
+ # A gateway profile id is only unique within the gateway account that issued it, so the same
21
+ # buyer needs a separate source under each payment method they pay through.
22
+ validates_uniqueness_of :gateway_payment_profile_id, scope: %i[type payment_method_id]
21
23
 
22
24
  #
23
25
  # Delegations
@@ -746,15 +746,25 @@ module Spree
746
746
  variants.active(current_currency).joins(:option_value_variants)
747
747
  end
748
748
 
749
+ # Units purchasable now across every variant: on hand, less what orders
750
+ # have taken and what checkouts are holding, at active locations, floored
751
+ # at zero per variant. Infinite when any variant does not track inventory.
749
752
  def total_on_hand
750
753
  @total_on_hand ||= if any_variants_not_track_inventory?
751
754
  BigDecimal::INFINITY
755
+ elsif variants.loaded?
756
+ variants.sum(&:total_on_hand)
752
757
  else
753
- if variants.loaded?
754
- variants.sum(&:total_on_hand)
755
- else
756
- stock_levels.loaded? ? stock_levels.sum(&:available_count) : stock_levels.sum('count_on_hand - allocated_count')
757
- end
758
+ # The same figure in one query: the per-variant floor
759
+ # needs the sums grouped before they are added up.
760
+ # Unordered, since the variants' position order cannot
761
+ # sit beside a GROUP BY on PostgreSQL. Holds count only
762
+ # while the store reserves stock, as on each variant.
763
+ levels = Spree::StockLevel.arel_table
764
+ purchasable = levels[:count_on_hand] - levels[:allocated_count]
765
+ purchasable -= levels[:reserved_count] if store_preference(:stock_reservations_enabled)
766
+ stock_levels.with_active_stock_location.unscope(:order).group(:variant_id).
767
+ sum(purchasable).values.sum { |count| [count, 0].max }
758
768
  end
759
769
  end
760
770
 
@@ -22,7 +22,7 @@ module Spree
22
22
  # clamped against its line's remaining discounted base, so the order net
23
23
  # can never go below zero.
24
24
  def compute_amount(line_item)
25
- return 0 unless promotion.line_item_actionable?(line_item.order, line_item)
25
+ return 0 unless promotion.line_item_actionable?(line_item.owner, line_item)
26
26
 
27
27
  [line_item.amount, compute(line_item)].min * -1
28
28
  end
@@ -51,7 +51,8 @@ module Spree
51
51
  before_validation :set_starts_at_to_current_time, if: -> { starts_at.blank? }
52
52
  after_commit :generate_coupon_codes, if: -> { multi_codes? }, on: [:create, :update]
53
53
  after_commit :remove_coupons, on: :update
54
- before_destroy :not_used?
54
+ before_destroy :detach_from_open_carts, prepend: true
55
+ before_destroy :not_used?, prepend: true
55
56
 
56
57
  #
57
58
  # Validations
@@ -372,8 +373,15 @@ module Spree
372
373
  end
373
374
 
374
375
  def apply_pending_rules_and_actions
375
- flush_pending_typed_association(:promotion_rules)
376
- flush_pending_typed_association(:promotion_actions)
376
+ flush_pending_typed_associations(:promotion_rules, :promotion_actions)
377
+ end
378
+
379
+ # Runs before the promotion's actions are destroyed, since the carts'
380
+ # discounts are tied back to the promotion through them.
381
+ def detach_from_open_carts
382
+ Spree::Cart.where(id: order_promotions.where.not(cart_id: nil).select(:cart_id)).find_each do |cart|
383
+ Spree::Promotions::DetachFromOwner.call(owner: cart, promotion: self, clear_coupon_code: true)
384
+ end
377
385
  end
378
386
 
379
387
  def not_used?
@@ -16,14 +16,20 @@ module Spree
16
16
  attr_reader :line_item, :order, :store
17
17
  attr_accessor :error, :success
18
18
 
19
- def initialize(order, line_item = nil)
19
+ # @param order [Spree::Cart, Spree::Order]
20
+ # @param line_item [Spree::LineItem, nil]
21
+ # @param excluded_promotion_ids [Array<String, Integer>] promotions to leave alone, e.g. one that is being removed
22
+ def initialize(order, line_item = nil, excluded_promotion_ids: [])
20
23
  @order = order
21
24
  @line_item = line_item
22
25
  @store = order.store
26
+ @excluded_promotion_ids = Array(excluded_promotion_ids).map(&:to_s)
23
27
  end
24
28
 
25
29
  def activate
26
30
  promotions.each do |promotion|
31
+ next if @excluded_promotion_ids.include?(promotion.id.to_s)
32
+
27
33
  if (line_item && promotion.eligible?(line_item)) || promotion.eligible?(order)
28
34
  promotion.activate(line_item: line_item, order: order)
29
35
  else
@@ -166,35 +166,7 @@ module Spree
166
166
  end
167
167
 
168
168
  def detach_promotion(promotion)
169
- # Order promotion has to be destroyed before line item removing
170
- order.promotions.delete(promotion)
171
-
172
- if promotion.multi_codes?
173
- promotion.coupon_codes.held_by(order).first&.remove_from_order
174
- else
175
- promotion.touch
176
- end
177
-
178
- remove_promotion_adjustments(promotion)
179
- remove_promotion_line_items(promotion)
180
- order.recalculate_totals!
181
- end
182
-
183
- def remove_promotion_adjustments(promotion)
184
- order.discounts.where(promotion_action_id: promotion.actions.pluck(:id)).destroy_all
185
- end
186
-
187
- def remove_promotion_line_items(promotion)
188
- create_line_item_actions_ids = promotion.actions.
189
- where(type: %w[Spree::Promotion::Actions::CreateLineItems Spree::Promotion::Actions::CreateLineItems]).pluck(:id)
190
-
191
- Spree::PromotionActionLineItem.where(promotion_action: create_line_item_actions_ids).find_each do |item|
192
- line_item = order.find_line_item_by_variant(item.variant)
193
- next if line_item.blank?
194
-
195
- remove_service = order.is_a?(Spree::Cart) ? Spree.cart_remove_item_service : Spree.order_remove_item_service
196
- remove_service.call(**{ (order.is_a?(Spree::Cart) ? :cart : :order) => order }, variant: item.variant, quantity: item.quantity)
197
- end
169
+ Spree::Promotions::DetachFromOwner.call(owner: order, promotion: promotion)
198
170
  end
199
171
 
200
172
  def handle_present_promotion
@@ -6,12 +6,19 @@ module Spree
6
6
 
7
7
  has_secure_token :token
8
8
 
9
+ # Personal data. Rows written before encryption was enabled stay readable
10
+ # and are encrypted when the token next rotates.
11
+ encrypts :ip_address, support_unencrypted_data: true if ActiveRecord::Encryption.config.has_primary_key?
12
+
9
13
  validates :user, :expires_at, presence: true
10
14
  # On create only: rows minted before the column exists keep their NULL and
11
15
  # stay loadable (they are simply unredeemable), while nothing new is born
12
16
  # without the surface it belongs to.
13
17
  validates :audience, presence: true, on: :create
14
18
 
19
+ # Starting a session and refreshing one both create a row.
20
+ after_create :record_user_activity
21
+
15
22
  scope :active, -> { where('expires_at > ?', Time.current) }
16
23
  scope :expired, -> { where('expires_at <= ?', Time.current) }
17
24
 
@@ -23,6 +30,12 @@ module Spree
23
30
  expires_at <= Time.current
24
31
  end
25
32
 
33
+ # Each refresh replaces the row, so its creation is the session's last use.
34
+ # @return [ActiveSupport::TimeWithZone]
35
+ def last_active_at
36
+ created_at
37
+ end
38
+
26
39
  # Rotate: destroy this token and create a new one.
27
40
  # Returns the new token.
28
41
  def rotate!(request_env: {})
@@ -74,5 +87,18 @@ module Spree
74
87
  rescue StandardError
75
88
  30.days
76
89
  end
90
+
91
+ private
92
+
93
+ # Outlives the session itself, which signing out deletes. Skips callbacks
94
+ # and +updated_at+: activity is not an edit to the account, and an older
95
+ # session committing last never moves it back. Users without the column
96
+ # (customers, custom admin classes) are left alone.
97
+ def record_user_activity
98
+ return unless user.has_attribute?(:last_active_at)
99
+
100
+ stale = user.class.where(id: user.id).where('last_active_at IS NULL OR last_active_at < ?', created_at)
101
+ stale.update_all(last_active_at: created_at)
102
+ end
77
103
  end
78
104
  end
@@ -71,7 +71,7 @@ module Spree
71
71
  has_many :stock_reservations
72
72
  end
73
73
 
74
- has_many :option_value_variants, class_name: 'Spree::OptionValueVariant'
74
+ has_many :option_value_variants, class_name: 'Spree::OptionValueVariant', dependent: :destroy
75
75
  has_many :option_values, through: :option_value_variants, dependent: :destroy, class_name: 'Spree::OptionValue'
76
76
 
77
77
  has_many :images, -> { order(:position) }, as: :viewable, dependent: :destroy, class_name: 'Spree::Media'
@@ -20,7 +20,7 @@ module Spree
20
20
 
21
21
  Spree::Newsletter::LinkUser.new(subscriber: subscriber, user: known_user).call
22
22
 
23
- if subscriber.email == current_user&.email
23
+ if current_user && subscriber.email.to_s.casecmp?(current_user.email.to_s)
24
24
  # User's email is already verified by login — skip the double opt-in.
25
25
  Spree::Newsletter::Verify.new(subscriber: subscriber).call
26
26
  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