spree_core 6.0.5 → 6.0.6

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 (82) hide show
  1. checksums.yaml +4 -4
  2. data/app/jobs/spree/payments/handle_modification_webhook_job.rb +93 -0
  3. data/app/jobs/spree/payments/handle_webhook_job.rb +4 -2
  4. data/app/maintenance_tasks/spree/maintenance_tasks/upgrade/backfill_settlement_statuses.rb +40 -0
  5. data/app/models/concerns/spree/customer_methods.rb +1 -1
  6. data/app/models/concerns/spree/product_scopes.rb +5 -2
  7. data/app/models/concerns/spree/purchase/payment_processing.rb +11 -0
  8. data/app/models/concerns/spree/purchase/purchase_order.rb +21 -0
  9. data/app/models/concerns/spree/purchase/totals.rb +3 -2
  10. data/app/models/concerns/spree/ransackable_attributes.rb +81 -4
  11. data/app/models/concerns/spree/settlement_status.rb +29 -0
  12. data/app/models/concerns/spree/stores/markets.rb +0 -30
  13. data/app/models/spree/base.rb +3 -3
  14. data/app/models/spree/category.rb +53 -32
  15. data/app/models/spree/collection_rule.rb +5 -1
  16. data/app/models/spree/export.rb +3 -1
  17. data/app/models/spree/exports/products.rb +9 -1
  18. data/app/models/spree/fulfillment.rb +23 -6
  19. data/app/models/spree/fulfillment_group.rb +2 -2
  20. data/app/models/spree/gateway/bogus.rb +41 -2
  21. data/app/models/spree/gift_card.rb +14 -2
  22. data/app/models/spree/media.rb +1 -1
  23. data/app/models/spree/option_type.rb +1 -0
  24. data/app/models/spree/order.rb +10 -4
  25. data/app/models/spree/order_group.rb +2 -2
  26. data/app/models/spree/payment/custom_events.rb +2 -1
  27. data/app/models/spree/payment/processing.rb +20 -3
  28. data/app/models/spree/payment.rb +186 -7
  29. data/app/models/spree/payment_capture_event.rb +2 -0
  30. data/app/models/spree/payment_method/store_credit.rb +6 -0
  31. data/app/models/spree/payment_method.rb +54 -2
  32. data/app/models/spree/payment_response.rb +19 -0
  33. data/app/models/spree/payment_session.rb +15 -3
  34. data/app/models/spree/payment_split.rb +14 -2
  35. data/app/models/spree/price.rb +1 -0
  36. data/app/models/spree/product.rb +4 -4
  37. data/app/models/spree/purchase_order.rb +20 -3
  38. data/app/models/spree/refund.rb +7 -1
  39. data/app/models/spree/return.rb +7 -1
  40. data/app/models/spree/search_provider/base.rb +10 -0
  41. data/app/models/spree/search_provider/database.rb +8 -5
  42. data/app/models/spree/store.rb +22 -0
  43. data/app/models/spree/store_credit.rb +1 -1
  44. data/app/models/spree/variant.rb +33 -0
  45. data/app/presenters/spree/csv/product_variant_presenter.rb +17 -8
  46. data/app/serializers/spree/emails/store_serializer.rb +1 -1
  47. data/app/services/spree/carts/split_by_seller.rb +4 -13
  48. data/app/services/spree/orders/create_from_cart.rb +2 -0
  49. data/app/services/spree/orders/update_statuses.rb +4 -2
  50. data/app/services/spree/store_credits/apply.rb +1 -1
  51. data/app/subscribers/spree/order_status_subscriber.rb +4 -3
  52. data/app/subscribers/spree/payment_split_subscriber.rb +39 -21
  53. data/app/subscribers/spree/seller_transfer_reversal_subscriber.rb +19 -7
  54. data/app/tools/spree/agent_tools/query_report.rb +116 -14
  55. data/app/workflows/spree/carts/complete.rb +1 -19
  56. data/app/workflows/spree/carts/recalculate_totals.rb +3 -3
  57. data/app/workflows/spree/orders/cancel.rb +19 -0
  58. data/app/workflows/spree/orders/complete.rb +7 -1
  59. data/app/workflows/spree/payments/capture.rb +99 -5
  60. data/app/workflows/spree/payments/handle_modification_webhook.rb +218 -0
  61. data/app/workflows/spree/payments/handle_webhook.rb +7 -1
  62. data/app/workflows/spree/payments/process.rb +47 -4
  63. data/app/workflows/spree/payments/void.rb +4 -1
  64. data/app/workflows/spree/products/approve.rb +17 -0
  65. data/app/workflows/spree/refunds/create.rb +10 -1
  66. data/app/workflows/spree/refunds/order_payments.rb +3 -1
  67. data/config/locales/be.yml +2 -2
  68. data/config/locales/bg.yml +4 -4
  69. data/config/locales/en.yml +8 -0
  70. data/config/locales/ru.yml +3 -3
  71. data/db/migrate/20261116100001_add_status_to_spree_payment_capture_events_and_refunds.rb +17 -0
  72. data/lib/spree/agent_tool.rb +11 -4
  73. data/lib/spree/core/dependencies.rb +1 -0
  74. data/lib/spree/core/version.rb +1 -1
  75. data/lib/spree/reporting/adapters/live.rb +69 -8
  76. data/lib/spree/reporting/default_vocabulary.rb +10 -4
  77. data/lib/spree/reporting/query.rb +4 -1
  78. data/lib/spree/reporting/registry.rb +50 -3
  79. data/lib/spree/testing_support/factories/payment_capture_event_factory.rb +10 -0
  80. data/lib/spree/testing_support/factories/refund_factory.rb +10 -0
  81. data/lib/spree/upgrades/5_6_to_6_0/manifest.yml +57 -0
  82. metadata +23 -4
@@ -163,7 +163,8 @@ module Spree
163
163
  # longer take money against it. Called for the sessions left pending when
164
164
  # an order is placed. The default leaves the session untouched: a
165
165
  # gateway that cannot cancel at the provider must not report as canceled
166
- # a session that can still be paid.
166
+ # a session that can still be paid. Adyen is the one exception: it cancels
167
+ # locally, which is a real cancel only for a session never made payable.
167
168
  #
168
169
  # Raise Spree::Core::GatewayError only for a refusal, such as a session
169
170
  # that was already paid. A timeout, a rate limit, an outage, or rejected
@@ -183,15 +184,56 @@ module Spree
183
184
  #
184
185
  # @param raw_body [String] the raw request body
185
186
  # @param headers [Hash] the request headers
186
- # @return [Hash, nil] normalized result or nil for unsupported events
187
+ # @return [Hash, nil] normalized result or nil for unsupported events.
188
+ # A session outcome:
187
189
  # { action: :captured/:authorized/:failed/:canceled,
188
190
  # payment_session: <Spree::PaymentSession>,
189
191
  # metadata: {} }
192
+ # or the outcome of a capture, void or refund the gateway answered
193
+ # +requested?+ for, naming its record by the reference
194
+ # {#modification_record} finds it with:
195
+ # { action: :capture_succeeded/:capture_failed/:void_succeeded/:void_failed/
196
+ # :refund_succeeded/:refund_failed,
197
+ # reference: 'the provider reference',
198
+ # metadata: { 'reason' => ... } }
199
+ # The record is not looked up here: the outcome can arrive before the
200
+ # request that writes it has finished, so the job looks it up and waits.
201
+ # A capture outcome may also name the payment its capture was asked
202
+ # for (+payment:+) and the amount taken (metadata 'amount'), so a
203
+ # capture whose answer never reached Spree is still recorded.
204
+ # A gateway that answers +requested?+ must report those outcomes here.
205
+ # metadata crosses a background job, so it must be JSON-safe with
206
+ # string keys; a failure's reason goes under 'reason'.
190
207
  # @raise [Spree::PaymentMethod::WebhookSignatureError] if signature is invalid
191
208
  def parse_webhook_event(raw_body, headers)
192
209
  raise ::NotImplementedError, 'You must implement parse_webhook_event method for this gateway.'
193
210
  end
194
211
 
212
+ # The record a modification outcome settles, or nil while it is not
213
+ # written yet. Reads only this method's payments.
214
+ #
215
+ # The default matches the reference against what core records from a
216
+ # +requested?+ answer: a capture event's or refund's +transaction_id+, and
217
+ # for a void the response code of a payment waiting on it (or already
218
+ # void, for a repeated delivery). Override when the provider names
219
+ # records otherwise.
220
+ #
221
+ # @param action [Symbol] one of the six modification outcomes
222
+ # @param reference [String] the reference from #parse_webhook_event
223
+ # @return [Spree::PaymentCaptureEvent, Spree::Payment, Spree::Refund, nil]
224
+ def modification_record(action, reference)
225
+ own_payments = Spree::Payment.where(payment_method_id: id)
226
+
227
+ case action.to_sym
228
+ when :capture_succeeded, :capture_failed
229
+ Spree::PaymentCaptureEvent.where(payment_id: own_payments.select(:id)).find_by(transaction_id: reference)
230
+ when :void_succeeded, :void_failed
231
+ own_payments.where(status: %w[requested void]).find_by(response_code: reference)
232
+ when :refund_succeeded, :refund_failed
233
+ Spree::Refund.where(payment_id: own_payments.select(:id)).find_by(transaction_id: reference)
234
+ end
235
+ end
236
+
195
237
  # Returns the webhook URL for this payment method.
196
238
  # @return [String, nil]
197
239
  def webhook_url
@@ -309,6 +351,16 @@ module Spree
309
351
  raise ::NotImplementedError, 'You must implement cancel method for this payment method.'
310
352
  end
311
353
 
354
+ # Whether #cancel voids the payment. A gateway that cannot void a
355
+ # captured charge refunds it through Refunds::Create instead, or leaves it
356
+ # standing when `refund:` is false, so the payment stays completed with
357
+ # any refund recorded against it.
358
+ #
359
+ # @param payment [Spree::Payment]
360
+ def cancel_voids?(payment)
361
+ can_void?(payment)
362
+ end
363
+
312
364
  # Whether the payment can be voided in its current state. Gateways that
313
365
  # cannot void a captured payment override this.
314
366
  # @param _payment [Spree::Payment]
@@ -35,6 +35,11 @@ module Spree
35
35
  # @return [Hash] CVV result with +"code"+ and +"message"+ keys
36
36
  attr_reader :cvv_result
37
37
 
38
+ # @return [String, nil] the provider's id for a capture it accepted but has
39
+ # not answered yet; a capture's authorization becomes the payment's
40
+ # response_code, so it cannot travel there
41
+ attr_reader :reference
42
+
38
43
  # @param success [Boolean] whether the gateway action succeeded
39
44
  # @param message [String] human-readable result message
40
45
  # @param params [Hash] raw key/value pairs returned by the gateway
@@ -43,12 +48,17 @@ module Spree
43
48
  # @option options [Hash] :avs_result must contain +:code+
44
49
  # @option options [Hash] :cvv_result may contain +:code+ and +:message+
45
50
  # @option options [Boolean] :test sandbox/test flag
51
+ # @option options [Boolean] :requested the provider accepted the request and
52
+ # reports its outcome later, by webhook
53
+ # @option options [String] :reference the provider's id for a requested capture
46
54
  def initialize(success, message, params = {}, options = {})
47
55
  @success = success
48
56
  @message = message
49
57
  @params = params.with_indifferent_access
50
58
  @test = options[:test] || false
51
59
  @authorization = options[:authorization]
60
+ @requested = options[:requested] || false
61
+ @reference = options[:reference]
52
62
  @avs_result = options[:avs_result] ? { 'code' => options[:avs_result][:code] } : { 'code' => nil }
53
63
  @cvv_result = if options[:cvv_result]
54
64
  { 'code' => options[:cvv_result][:code], 'message' => options[:cvv_result][:message] }
@@ -62,6 +72,15 @@ module Spree
62
72
  @success
63
73
  end
64
74
 
75
+ # Whether the provider accepted the request and will report its outcome by
76
+ # webhook. Only a gateway that returns that outcome from
77
+ # +parse_webhook_event+ may answer this.
78
+ #
79
+ # @return [Boolean]
80
+ def requested?
81
+ @requested
82
+ end
83
+
65
84
  # @return [Boolean] whether the response came from a test/sandbox environment
66
85
  def test?
67
86
  @test
@@ -115,6 +115,16 @@ module Spree
115
115
  payment.metadata.merge!(metadata.stringify_keys) if metadata.present?
116
116
  end
117
117
 
118
+ # The provider's id for the capture when the payment settles as captured,
119
+ # written on its capture event so a late capture failure can find it.
120
+ # Called inside the settlement lock, so it must not perform provider I/O.
121
+ #
122
+ # @param payment [Spree::Payment] the payment being settled
123
+ # @return [String, nil]
124
+ def capture_reference_for_settlement(_payment)
125
+ nil
126
+ end
127
+
118
128
  # Fetches whatever settlement will need from the provider, so a caller
119
129
  # that settles inside a lock (the webhook path) holds it across no
120
130
  # provider I/O. Gateway session subclasses override; no-op by default.
@@ -149,10 +159,12 @@ module Spree
149
159
  # been cached on this instance before the lock (a concurrent
150
160
  # settlement could have completed it), but reload would discard
151
161
  # in-memory state like skip_source_requirement.
152
- already_completed = settled_payment.completed? ||
153
- Spree::Payment.where(id: settled_payment.id, status: 'completed').exists?
162
+ # A requested payment waits on its provider's answer to a capture or
163
+ # void, so a redelivered authorization must not move it.
164
+ already_settled = settled_payment.status.in?(Spree::Payment::SETTLED_OR_WAITING_STATUSES) ||
165
+ Spree::Payment.exists?(id: settled_payment.id, status: Spree::Payment::SETTLED_OR_WAITING_STATUSES)
154
166
 
155
- settled_payment.confirm!(captured: captured) unless already_completed
167
+ settled_payment.confirm!(captured: captured, capture_reference: capture_reference_for_settlement(settled_payment)) unless already_settled
156
168
  end
157
169
 
158
170
  settled_payment
@@ -68,11 +68,12 @@ module Spree
68
68
  # instead of the denormalized column, because that column is written by a
69
69
  # subscriber after the fact: two refunds landing together would each read a
70
70
  # share that still looked unrefunded. {Spree::Refunds::Create} bounds every
71
- # refund by this under the payment's lock.
71
+ # refund by this under the payment's lock. A refund still waiting on its
72
+ # provider counts, so its amount cannot be refunded twice.
72
73
  #
73
74
  # @return [BigDecimal]
74
75
  def refundable_amount
75
- already_refunded = Spree::Refund.where(payment_id: payment_id, order_id: order_id).sum(:amount)
76
+ already_refunded = Spree::Refund.not_failed.where(payment_id: payment_id, order_id: order_id).sum(:amount)
76
77
  captured_amount - already_refunded
77
78
  end
78
79
 
@@ -87,6 +88,17 @@ module Spree
87
88
  authorized_amount - captured_amount - claimed_amount
88
89
  end
89
90
 
91
+ # Turns a claim into what it turned out to be: money the gateway took, or
92
+ # nothing at all.
93
+ #
94
+ # @param amount [BigDecimal] how much of the claim settles
95
+ # @param captured [Boolean] whether the gateway took it
96
+ def settle_claim!(amount, captured:)
97
+ attributes = { claimed_amount: claimed_amount - amount }
98
+ attributes[:captured_amount] = captured_amount + amount if captured
99
+ update!(attributes)
100
+ end
101
+
90
102
  # @return [Boolean] whether a charge for this share is still in flight —
91
103
  # reserved by a parcel, and not yet confirmed by the gateway
92
104
  def capture_in_flight?
@@ -88,6 +88,7 @@ module Spree
88
88
  self.whitelisted_ransackable_attributes = %w[amount compare_at_amount currency min_quantity price_list_id variant_id]
89
89
  self.whitelisted_ransackable_associations = %w[variant price_list]
90
90
  self.whitelisted_ransackable_scopes = %i[search]
91
+ self.ransackable_scope_types = { 'search' => 'text' }
91
92
 
92
93
  # Free-text search delegated to `Spree::Variant.search` (SKU + product
93
94
  # name + option-value presentation), wrapped in a subquery so that
@@ -396,7 +396,7 @@ module Spree
396
396
  'in_taxon' => 'id', 'in_category' => 'id', 'in_collection' => 'id',
397
397
  'in_categories' => { list: 'id' }, 'with_option_value_ids' => { list: 'id' },
398
398
  'price_between' => %w[decimal decimal], 'price_lte' => 'decimal', 'price_gte' => 'decimal',
399
- 'ascend_by_price' => 'boolean', 'descend_by_price' => 'boolean'
399
+ 'ascend_by_price' => 'boolean', 'descend_by_price' => 'boolean', 'search' => 'text'
400
400
  }
401
401
 
402
402
  # All product-level convenience attributes delegate to the default variant —
@@ -649,9 +649,9 @@ module Spree
649
649
  # seller check: a variant from a seller who is suspended, still onboarding
650
650
  # or away is not for sale, so it cannot be what the product displays.
651
651
  def first_available_variant(currency)
652
- sellable_variants.find do |variant|
653
- variant.purchasable? && variant.price_in(currency).amount.present?
654
- end
652
+ variants_to_check = sellable_variants
653
+ Spree::Stock::Quantifier.preload(variants_to_check)
654
+ variants_to_check.find { |variant| variant.purchasable_in?(currency) }
655
655
  end
656
656
 
657
657
  # Whether the shop price differs between this product's variants. Reads
@@ -51,9 +51,11 @@ module Spree
51
51
 
52
52
  # Overdue and past-cancel-by read the calendar date in the server's zone;
53
53
  # a supplier's promise is a day, and a few hours either side of midnight
54
- # is not what a merchant is filtering for.
55
- scope :overdue, -> { open.where(arel_table[:expected_at].lt(Date.current)) }
56
- scope :past_cancel_by, -> { open.where(arel_table[:cancel_by].lt(Date.current)) }
54
+ # is not what a merchant is filtering for. Two-state scopes (see
55
+ # Spree::Base.ransack_flag): the false side is the open orders not yet
56
+ # late, so a closed order is on neither side.
57
+ scope :overdue, ->(*values) { open_by_date(:expected_at, Spree::Base.ransack_flag(*values)) }
58
+ scope :past_cancel_by, ->(*values) { open_by_date(:cancel_by, Spree::Base.ransack_flag(*values)) }
57
59
 
58
60
  self.whitelisted_ransackable_attributes = %w[number status currency reference expected_at
59
61
  cancel_by ordered_at received_at closed_short_at
@@ -61,6 +63,21 @@ module Spree
61
63
  search_by :number, :reference
62
64
  self.whitelisted_ransackable_scopes = %w[open closed overdue past_cancel_by]
63
65
  self.ransackable_scope_types = %w[open closed overdue past_cancel_by].index_with('boolean')
66
+
67
+ def self.ransackable_scopes_skip_sanitize_args
68
+ %i[overdue past_cancel_by]
69
+ end
70
+
71
+ # @param column [Symbol] the date the supplier promised against
72
+ # @param late [Boolean, nil] true for open orders past it, false for open
73
+ # orders not past it (or without one), nil for every order
74
+ # @return [ActiveRecord::Relation]
75
+ def self.open_by_date(column, late)
76
+ return all if late.nil?
77
+
78
+ date = arel_table[column]
79
+ late ? open.where(date.lt(Date.current)) : open.where(date.gteq(Date.current).or(date.eq(nil)))
80
+ end
64
81
  self.whitelisted_ransackable_associations = %w[supplier destination_location items]
65
82
 
66
83
  # What the supplier will invoice for everything ordered.
@@ -6,6 +6,7 @@ module Spree
6
6
  include Spree::HasCustomFields
7
7
  include Spree::Metadata
8
8
  include Spree::CanonicalDecimals
9
+ include Spree::SettlementStatus
9
10
 
10
11
  canonical_decimals :amount
11
12
  include Spree::InstrumentsGatewayCalls
@@ -14,6 +15,7 @@ module Spree
14
15
  end
15
16
 
16
17
  publishes_lifecycle_events
18
+ publishes_events :requested, :failed
17
19
 
18
20
  belongs_to :payment, inverse_of: :refunds
19
21
  # Which order is being put right. A refund against an ordinary payment
@@ -115,6 +117,9 @@ module Spree
115
117
  # blank transaction_id means the credit has not happened yet; a present
116
118
  # one makes this a no-op, so replays are safe.
117
119
  #
120
+ # A gateway that answers +requested?+ leaves the refund requested until
121
+ # its webhook completes or fails it.
122
+ #
118
123
  # @raise [Spree::Core::GatewayError] when the gateway declines or is down
119
124
  # @return [true]
120
125
  def perform!
@@ -123,7 +128,8 @@ module Spree
123
128
  @response = process!(payment.payment_method.gateway_amount(amount, currency))
124
129
 
125
130
  self.transaction_id = @response.authorization
126
- update_columns(transaction_id: transaction_id)
131
+ self.status = @response.requested? ? 'requested' : 'completed'
132
+ update_columns(transaction_id: transaction_id, status: status)
127
133
  update_order
128
134
  true
129
135
  end
@@ -164,8 +164,14 @@ module Spree
164
164
  # What has actually been refunded so far — a return can be refunded in
165
165
  # more than one step (part to store credit, part to the card), and store
166
166
  # credit is its own ledger rather than a Spree::Refund row.
167
+ # A failed refund gave nothing back; one still requested holds its amount.
167
168
  def refunded_total
168
- ledger_total(:refunds) + ledger_total(:store_credits)
169
+ refunds_given = if read_association_in_memory?(:refunds)
170
+ refunds.reject(&:failed?).sum(0.to_d, &:amount)
171
+ else
172
+ refunds.not_failed.sum(:amount)
173
+ end
174
+ refunds_given + ledger_total(:store_credits)
169
175
  end
170
176
 
171
177
  def refundable_total
@@ -108,6 +108,16 @@ module Spree
108
108
  def currency
109
109
  Spree::Current.currency || store.default_market&.currency
110
110
  end
111
+
112
+ def in_stock_filter?(filters)
113
+ ActiveModel::Type::Boolean.new.cast(filters['in_stock'] || filters[:in_stock]) == true
114
+ end
115
+
116
+ def option_filter_variants(filters)
117
+ return unless audience == :store
118
+
119
+ Spree::Variant.for_option_filters(currency, in_stock: in_stock_filter?(filters), store: store)
120
+ end
111
121
  end
112
122
  end
113
123
  end
@@ -16,8 +16,9 @@ module Spree
16
16
  # active
17
17
  grouping = manual_sort_grouping(filters)
18
18
 
19
+ variants = option_filter_variants(filters)
19
20
  scope = apply_search_and_filters(scope, query: query, filters: filters)
20
- scope = scope.with_option_value_ids(Array(option_value_ids)) if option_value_ids.present?
21
+ scope = scope.with_option_value_ids(Array(option_value_ids), variants: variants) if option_value_ids.present?
21
22
 
22
23
  # Total count (before sorting to avoid computed column conflicts with count)
23
24
  total = scope.distinct.count
@@ -40,18 +41,19 @@ module Spree
40
41
  category = filters.delete('_category') || filters.delete(:_category)
41
42
  collection = filters.delete('_collection') || filters.delete(:_collection)
42
43
  option_value_ids = Array(filters.delete('with_option_value_ids') || filters.delete(:with_option_value_ids))
44
+ variants = option_filter_variants(filters)
43
45
 
44
46
  # Apply text search + ransack filters (without option values)
45
47
  scope_before_options = apply_search_and_filters(scope, query: query, filters: filters)
46
48
 
47
49
  # Apply option value filters for the final scope
48
50
  scope_with_options = if option_value_ids.present?
49
- scope_before_options.with_option_value_ids(option_value_ids)
51
+ scope_before_options.with_option_value_ids(option_value_ids, variants: variants)
50
52
  else
51
53
  scope_before_options
52
54
  end
53
55
 
54
- filter_facets = build_facets(scope_with_options, category: category, sort_order: collection&.sort_order, option_value_ids: option_value_ids, scope_before_options: scope_before_options)
56
+ filter_facets = build_facets(scope_with_options, category: category, sort_order: collection&.sort_order, option_value_ids: option_value_ids, scope_before_options: scope_before_options, variants: variants)
55
57
  filter_facets[:sort_options] = filter_facets[:sort_options] + custom_field_sort_options
56
58
 
57
59
  FiltersResult.new(
@@ -83,7 +85,7 @@ module Spree
83
85
  Pagy::Offset.new(count: count, page: page, limit: limit)
84
86
  end
85
87
 
86
- def build_facets(scope, category: nil, sort_order: nil, option_value_ids: [], scope_before_options: nil)
88
+ def build_facets(scope, category: nil, sort_order: nil, option_value_ids: [], scope_before_options: nil, variants: nil)
87
89
  return { filters: [], sort_options: built_in_sort_options, default_sort: 'manual', total_count: scope.distinct.count } unless defined?(Spree::Api::V3::FiltersAggregator)
88
90
 
89
91
  Spree::Api::V3::FiltersAggregator.new(
@@ -92,7 +94,8 @@ module Spree
92
94
  category: category,
93
95
  sort_order: sort_order,
94
96
  option_value_ids: option_value_ids,
95
- scope_before_options: scope_before_options || scope
97
+ scope_before_options: scope_before_options || scope,
98
+ variants: variants
96
99
  ).call
97
100
  end
98
101
 
@@ -32,6 +32,11 @@ module Spree
32
32
  acts_as_paranoid
33
33
  friendly_id :code, use: [:slugged], slug_column: :code, routes: :normal
34
34
 
35
+ # Headless storefronts cache the store's name, SEO fields and logo, and
36
+ # expire them on `store.updated`. An installation runs one store, which is
37
+ # never created or deleted while live, so those events are left out.
38
+ publishes_lifecycle_events only: [:update]
39
+
35
40
  #
36
41
  # Translations
37
42
  #
@@ -777,8 +782,25 @@ module Spree
777
782
  end
778
783
  end
779
784
 
785
+ # The payload is the store in its default language, whichever language
786
+ # the change was written in: a translation saved under `de` still
787
+ # announces the store as storefronts show it by default.
788
+ def event_payload_for(event_name, **params)
789
+ Spree::Current.with_content_locale(default_locale) do
790
+ ::Mobility.with_locale(default_locale) { super }
791
+ end
792
+ end
793
+
780
794
  private
781
795
 
796
+ # A store's events belong to it, whichever store the caller is working in,
797
+ # so they reach this store's webhook endpoints.
798
+ def in_event_store(&block)
799
+ return block.call if Spree::Current.store == self
800
+
801
+ Spree::Current.with_store(self, &block)
802
+ end
803
+
782
804
  # Products without a profile fall back to this one, so it must exist
783
805
  # from the store's first moment.
784
806
  def create_default_delivery_profile
@@ -118,7 +118,7 @@ module Spree
118
118
  # Two-state scopes: see Spree::Base.ransack_flag? for why the cast is
119
119
  # opted out of here and done inside each scope instead.
120
120
  def self.ransackable_scopes_skip_sanitize_args
121
- %i[outstanding from_gift_card]
121
+ super | %w[outstanding from_gift_card]
122
122
  end
123
123
 
124
124
  def amount_remaining
@@ -176,6 +176,28 @@ module Spree
176
176
  scope :backorderable, -> { left_joins(:stock_levels).where(Spree::StockLevel.table_name => { backorderable: true }) }
177
177
  scope :in_stock_or_backorderable, -> { in_stock.or(backorderable) }
178
178
 
179
+ # The variants a storefront option filter matches and counts. The rules
180
+ # +Product.available+ (a base price, unless the store lists products
181
+ # without one) and +Product.in_stock+ apply to a product as a whole, so a
182
+ # value carried only by an unpriced, sold-out or discontinued variant
183
+ # would otherwise offer the shopper a product they cannot buy in it.
184
+ #
185
+ # @param currency [String, nil] defaults to the current currency
186
+ # @param in_stock [Boolean] whether the shopper asked for in-stock products
187
+ # @param store [Spree::Store, nil] whose price setting applies
188
+ # @return [ActiveRecord::Relation<Spree::Variant>]
189
+ def self.for_option_filters(currency = nil, in_stock: false, store: Spree::Current.store)
190
+ scope = not_discontinued
191
+
192
+ unless Spree::StorePreferences.read(store, :show_products_without_price)
193
+ priced = for_currency_and_available_price_amount(currency || Spree::Current.currency)
194
+ scope = scope.where(id: priced.select(:id))
195
+ end
196
+
197
+ scope = scope.where(id: in_stock_or_backorderable.select(:id)) if in_stock
198
+ scope
199
+ end
200
+
179
201
  # Variants one warehouse could actually send: it holds a level for them
180
202
  # with something available on it. Written for the transfer form's picker,
181
203
  # which would otherwise offer SKUs the source has none of — and
@@ -960,6 +982,17 @@ module Spree
960
982
  in_stock? || oversellable_now?
961
983
  end
962
984
 
985
+ # Whether a shopper could put this in a cart in the currency. Stock alone
986
+ # is not enough: the cart refuses a variant unless it has a base price
987
+ # there or a price list or pricing provider quoted one for the shopper.
988
+ #
989
+ # @param currency [String]
990
+ # @param quote [Spree::Price, nil] the price resolved for the shopper, when known
991
+ # @return [Boolean]
992
+ def purchasable_in?(currency, quote: nil)
993
+ purchasable? && (quote&.amount.present? || amount_in(currency).present?)
994
+ end
995
+
963
996
  # Whether the variant can currently be bought by overselling — via
964
997
  # backorder or pre-order. Unlimited when +backorder_limit+ is nil (empty =
965
998
  # no cap); with a limit, purchasable only while the oversell allowance
@@ -1,8 +1,6 @@
1
1
  module Spree
2
2
  module CSV
3
3
  class ProductVariantPresenter
4
- include Spree::ImagesHelper
5
-
6
4
  CSV_HEADERS = [
7
5
  'product_id',
8
6
  'sku',
@@ -76,7 +74,7 @@ module Spree
76
74
  # For the primary variant row (when the index is zero), product-level details such as name,
77
75
  # slug, status, seller name, description, meta tags, and tag/label lists are included.
78
76
  # In all cases, variant-specific attributes (e.g., id, SKU, pricing, dimensions, weight,
79
- # availability dates, inventory count, shipping category, tax category, image URLs via original_url,
77
+ # availability dates, inventory count, shipping category, tax category, original image URLs,
80
78
  # and the first three option types and corresponding option values) are appended.
81
79
  # Additionally, when the index is zero, associated categories and properties are added.
82
80
  #
@@ -121,9 +119,9 @@ module Spree
121
119
  nil,
122
120
  variant.tax_category&.name,
123
121
  product.product_type&.name,
124
- spree_image_url(variant.images[0], image_url_options),
125
- spree_image_url(variant.images[1], image_url_options),
126
- spree_image_url(variant.images[2], image_url_options),
122
+ image_urls[0],
123
+ image_urls[1],
124
+ image_urls[2],
127
125
  option_type(0)&.label,
128
126
  option_value(option_type(0)),
129
127
  option_type(1)&.label,
@@ -207,8 +205,19 @@ module Spree
207
205
  @default_stock_level = variant.stock_levels.find { |level| level.stock_location_id == location.id }
208
206
  end
209
207
 
210
- def image_url_options
211
- { variant: :xlarge }
208
+ # The original files, which the import downloads back onto the row's
209
+ # variant: the media linked to that variant, or on the product's first
210
+ # row, when it has none, the product's own gallery so unlinked uploads
211
+ # survive. Videos are left out — the import saves every URL as an image.
212
+ def image_urls
213
+ @image_urls ||= begin
214
+ media = variant.gallery_media.to_a
215
+ media = product.media.to_a if media.empty? && index.zero?
216
+
217
+ media.select { |image| image.image? && image.attached? }.first(3).map do |image|
218
+ Rails.application.routes.url_helpers.cdn_image_url(image.attachment)
219
+ end
220
+ end
212
221
  end
213
222
  end
214
223
  end
@@ -12,7 +12,7 @@ module Spree
12
12
  attribute :support_email, &:support_email_address
13
13
 
14
14
  attribute :logo_url do |store|
15
- spree_image_url(store.email_logo, height: LOGO_HEIGHT)
15
+ spree_image_url(store.email_logo, height: LOGO_HEIGHT, format: 'png')
16
16
  end
17
17
 
18
18
  # The width the logo shows at, from its proportions. Nil until the file
@@ -142,7 +142,10 @@ module Spree
142
142
  move_typed_lines(sibling, line_item_ids, divided)
143
143
  copy_promotions(source_order, sibling)
144
144
  copy_tax_identifier(source_order, sibling)
145
- copy_po_document(source_order, sibling)
145
+ # The PO number rides along in CARRIED_TO_SIBLING, so the document
146
+ # behind it has to as well — otherwise a buyer whose checkout splits
147
+ # sees their reference on every order and the paperwork on only one.
148
+ sibling.copy_po_document_from!(source_order)
146
149
 
147
150
  sibling.reload
148
151
  end
@@ -388,18 +391,6 @@ module Spree
388
391
  sibling.create_tax_identifier!(attributes)
389
392
  end
390
393
 
391
- # The PO number rides along in CARRIED_TO_SIBLING, so the document behind
392
- # it has to as well — otherwise a buyer whose checkout splits sees their
393
- # reference on every order and the paperwork on only one. The same blob,
394
- # like the completion copy.
395
- def copy_po_document(source_order, sibling)
396
- return unless source_order.po_document.attached?
397
-
398
- return if sibling.po_document.attach(source_order.po_document.blob)
399
-
400
- raise ActiveRecord::RecordInvalid, sibling
401
- end
402
-
403
394
  # An order-level fee was charged for the checkout as a whole, so it is
404
395
  # apportioned across the children by what each is worth. Largest-remainder
405
396
  # so the shares add back up to what the customer was charged, and the
@@ -24,6 +24,7 @@ module Spree
24
24
  ApplicationRecord.transaction do
25
25
  order = build_order(cart, customer: customer, created_by: created_by)
26
26
  order.save!
27
+ order.copy_po_document_from!(cart)
27
28
 
28
29
  line_item_map = copy_line_items(cart, order)
29
30
  Spree.cart_copiers.each { |copier| copier.call(cart: cart, order: order, line_item_map: line_item_map) }
@@ -53,6 +54,7 @@ module Spree
53
54
  channel: cart.channel,
54
55
  company: cart.resolved_company,
55
56
  customer_note: cart.customer_note,
57
+ po_number: cart.po_number,
56
58
  metadata: cart.metadata.to_h,
57
59
  preferred_stock_location_id: cart.preferred_stock_location_id,
58
60
  token: Spree::GenerateToken.new.call(Spree::Order),
@@ -72,10 +72,12 @@ module Spree
72
72
  credited = order.store_credit_refunds.sum(:amount)
73
73
 
74
74
  unless order.order_group_id.present?
75
+ # A payment waiting on its provider's answer to a capture or void
76
+ # still holds its authorization.
75
77
  return [
76
78
  order.payments.valid.completed.sum(:amount),
77
- order.payments.valid.pending.sum(:amount),
78
- order.refunds.sum(:amount) + credited
79
+ order.payments.valid.with_status(:pending, :requested).sum(:amount),
80
+ order.refunds.completed_or_unset.sum(:amount) + credited
79
81
  ]
80
82
  end
81
83
 
@@ -33,7 +33,7 @@ module Spree
33
33
  @order.update_hooks.each { |hook| @order.send(hook) } if @order.respond_to?(:update_hooks)
34
34
  success(@order)
35
35
  else
36
- failure(@order)
36
+ failure(@order, I18n.t('spree.store_credit_not_applied'))
37
37
  end
38
38
  end
39
39
 
@@ -14,7 +14,7 @@ module Spree
14
14
  class OrderStatusSubscriber < Spree::Subscriber
15
15
  subscribes_to 'payment.created', 'payment.updated', 'payment.deleted',
16
16
  'payment.completed', 'payment.captured', 'payment.voided',
17
- 'refund.created', 'refund.updated',
17
+ 'refund.created', 'refund.updated', 'payment.refunded', 'refund.failed',
18
18
  'store_credit.created', 'store_credit.updated', 'store_credit.deleted',
19
19
  'fulfillment.created', 'fulfillment.updated', 'fulfillment.deleted',
20
20
  'return.received', 'return.refunded', 'return.canceled',
@@ -23,10 +23,11 @@ module Spree
23
23
  # Events whose payload changes what the customer has actually paid, so
24
24
  # payment_total has to be re-summed before statuses derive from it.
25
25
  # Store credit is not one of them: the money stayed with the store, and
26
- # payment_total is what came in through payments.
26
+ # payment_total is what came in through payments. A refund counts once it
27
+ # completes (payment.refunded) and stops counting if it fails.
27
28
  MONEY_EVENTS = %w[
28
29
  payment.created payment.updated payment.deleted payment.completed
29
- payment.voided refund.created refund.updated
30
+ payment.voided refund.created refund.updated payment.refunded refund.failed
30
31
  return.refunded
31
32
  ].freeze
32
33