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
@@ -4,12 +4,20 @@ module Spree
4
4
  # to avoid N+1 queries
5
5
  def scope_includes
6
6
  includes = [:tax_category, :option_types, :categories, { variants: variant_includes }]
7
+ includes << { media: media_includes }
7
8
  includes << { custom_fields: :custom_field_definition }
8
9
  includes
9
10
  end
10
11
 
11
12
  def variant_includes
12
- [:images, :prices, { stock_levels: :stock_location, option_values: [:option_type] }]
13
+ [
14
+ :prices, :variant_media,
15
+ { images: media_includes, associated_media: media_includes, stock_levels: :stock_location, option_values: [:option_type] }
16
+ ]
17
+ end
18
+
19
+ def media_includes
20
+ { attachment_attachment: :blob }
13
21
  end
14
22
 
15
23
  def multi_line_csv?
@@ -474,7 +474,17 @@ module Spree
474
474
  fulfillment_items.includes(:line_item).map(&:line_item).uniq
475
475
  end
476
476
 
477
- ManifestItem = Struct.new(:line_item, :variant, :quantity, :states)
477
+ ManifestItem = Struct.new(:line_item, :variant, :quantity, :states) do
478
+ # An exchange replacement rides on the original line item, so it is priced
479
+ # as its own variant rather than at the line's price.
480
+ #
481
+ # @return [BigDecimal]
482
+ def price
483
+ return line_item.price if variant.nil? || variant.id == line_item.variant_id
484
+
485
+ variant.price_in(line_item.currency).amount || line_item.price
486
+ end
487
+ end
478
488
 
479
489
  def manifest
480
490
  # Grouping by the ID means that we don't have to call out to the association accessor
@@ -521,6 +531,14 @@ module Spree
521
531
  sort_by(&:uncaptured_amount).reverse
522
532
 
523
533
  shipment_to_pay = final_price_with_items
534
+ # The capture workflow refuses an amount above what the order still
535
+ # owes, so a parcel priced above it (the total came down after
536
+ # authorization) takes the balance rather than failing the dispatch. A
537
+ # shared payment is bounded by this order's share instead, in #capture_from.
538
+ # Read from the payment rows, as the workflow does: an owner loaded
539
+ # before an earlier parcel captured still carries that parcel's balance.
540
+ owed = pending_payments.first&.amount_owed_by_order(including_in_flight: false) unless grouped_owner?
541
+ shipment_to_pay = [shipment_to_pay, owed].min if owed
524
542
  payments_amount = 0
525
543
 
526
544
  payments_pool = pending_payments.each_with_object([]) do |payment, pool|
@@ -874,6 +892,9 @@ module Spree
874
892
 
875
893
  begin
876
894
  capture_at_gateway(payment, bounded)
895
+ # The provider answers by webhook: the claim stays until then, which
896
+ # records the share as captured or releases it.
897
+ return bounded if payment.reload.requested?
877
898
  rescue StandardError
878
899
  # Released only when the money truly never moved. The capture workflow
879
900
  # keeps working after the charge commits — it authorizes the remainder
@@ -893,11 +914,7 @@ module Spree
893
914
  # caller in the rescue path is already raising the reason the capture
894
915
  # failed, and losing that to a bookkeeping error would hide it.
895
916
  def settle_share(split, amount, captured:)
896
- split.with_lock do
897
- attributes = { claimed_amount: split.claimed_amount - amount }
898
- attributes[:captured_amount] = split.captured_amount + amount if captured
899
- split.update!(attributes)
900
- end
917
+ split.with_lock { split.settle_claim!(amount, captured: captured) }
901
918
  rescue StandardError => e
902
919
  Rails.error.report(e, handled: true, context: { payment_split_id: split.id }, source: 'spree.core')
903
920
  end
@@ -103,8 +103,8 @@ module Spree
103
103
  #
104
104
  # @return [Array<Spree::Fulfillment::ManifestItem>]
105
105
  def manifest
106
- fulfillments.flat_map(&:manifest).group_by(&:line_item).map do |line_item, items|
107
- Spree::Fulfillment::ManifestItem.new(line_item, line_item.variant, items.sum(&:quantity), nil)
106
+ fulfillments.flat_map(&:manifest).group_by { |item| [item.line_item, item.variant] }.map do |(line_item, variant), items|
107
+ Spree::Fulfillment::ManifestItem.new(line_item, variant, items.sum(&:quantity), nil)
108
108
  end
109
109
  end
110
110
 
@@ -13,6 +13,9 @@ module Spree
13
13
 
14
14
  preference :dummy_key, :string, default: 'PUBLICKEY123'
15
15
  preference :dummy_secret_key, :password, default: 'SECRETKEY123'
16
+ # Answers captures, voids and refunds the way a provider that reports
17
+ # their outcome by webhook does, so core can test that path without one.
18
+ preference :requested_mode, :boolean, default: false
16
19
 
17
20
  def provider_class
18
21
  self.class
@@ -50,23 +53,39 @@ module Spree
50
53
  end
51
54
 
52
55
  def credit(_money, _credit_card, _response_code, _options = {})
56
+ if preferred_requested_mode
57
+ return Spree::PaymentResponse.new(true, 'Bogus Gateway: Refund requested', {},
58
+ test: true, requested: true, authorization: "BGS-refund-#{SecureRandom.hex(6)}")
59
+ end
60
+
53
61
  Spree::PaymentResponse.new(true, 'Bogus Gateway: Forced success', {}, test: true, authorization: generate_authorization)
54
62
  end
55
63
 
56
64
  def capture(_money, authorization, _gateway_options)
57
65
  if authorization&.start_with?('BGS-')
58
- Spree::PaymentResponse.new(true, 'Bogus Gateway: Forced success', {}, test: true)
66
+ return Spree::PaymentResponse.new(true, 'Bogus Gateway: Forced success', {}, test: true) unless preferred_requested_mode
67
+
68
+ Spree::PaymentResponse.new(true, 'Bogus Gateway: Capture requested', {},
69
+ test: true, requested: true, reference: "BGS-capture-#{SecureRandom.hex(6)}")
59
70
  else
60
71
  Spree::PaymentResponse.new(false, 'Bogus Gateway: Forced failure', error: 'Bogus Gateway: Forced failure', test: true)
61
72
  end
62
73
  end
63
74
 
64
75
  def void(_response_code, _credit_card, _options = {})
76
+ return Spree::PaymentResponse.new(true, 'Bogus Gateway: Void requested', {}, test: true, requested: true) if preferred_requested_mode
77
+
65
78
  Spree::PaymentResponse.new(true, 'Bogus Gateway: Forced success', {}, test: true, authorization: "void-#{generate_authorization}")
66
79
  end
67
80
 
68
81
  # Voids outright, so there is no captured charge for `refund:` to govern.
69
- def cancel(_response_code, _payment = nil, refund: true)
82
+ # In requested mode only an uncaptured payment waits: a captured one has no
83
+ # refund recorded for an outcome to settle.
84
+ def cancel(_response_code, payment = nil, refund: true)
85
+ if preferred_requested_mode && !payment&.completed?
86
+ return Spree::PaymentResponse.new(true, 'Bogus Gateway: Cancel requested', {}, test: true, requested: true)
87
+ end
88
+
70
89
  Spree::PaymentResponse.new(true, 'Bogus Gateway: Forced success', {}, test: true, authorization: generate_authorization)
71
90
  end
72
91
 
@@ -167,6 +186,26 @@ module Spree
167
186
  %w(capture void credit)
168
187
  end
169
188
 
189
+ # In requested mode, accepts a plain JSON outcome naming the action and the
190
+ # record's reference, so specs and the dashboard's end-to-end test can
191
+ # answer a requested capture, void or refund through the webhook endpoint:
192
+ # { "action": "capture_succeeded", "reference": "<capture event transaction id>" }
193
+ # { "action": "void_failed", "reference": "<payment response code>", "reason": "..." }
194
+ # { "action": "refund_succeeded", "reference": "<refund transaction id>" }
195
+ def parse_webhook_event(raw_body, headers)
196
+ return super unless preferred_requested_mode
197
+
198
+ body = JSON.parse(raw_body)
199
+ action = body['action'].to_s
200
+ reference = body['reference'].to_s
201
+ return if reference.blank? || Spree::Payments::HandleModificationWebhook::OUTCOME_RECORDS.keys.map(&:to_s).exclude?(action)
202
+
203
+ metadata = body['reason'].present? ? { 'reason' => body['reason'].to_s } : {}
204
+ { action: action.to_sym, reference: reference, metadata: metadata }
205
+ rescue JSON::ParserError
206
+ raise WebhookSignatureError
207
+ end
208
+
170
209
  private
171
210
 
172
211
  def generate_authorization
@@ -35,6 +35,7 @@ module Spree
35
35
  validates :currency, presence: true
36
36
  validates :amount, presence: true, numericality: { greater_than: 0 }
37
37
  validates :amount_used, :amount_authorized, presence: true, numericality: { greater_than_or_equal_to: 0 }
38
+ validate :amount_and_currency_unchanged_once_used, on: :update
38
39
 
39
40
  #
40
41
  # Associations
@@ -94,8 +95,7 @@ module Spree
94
95
  end
95
96
 
96
97
  # What the card can still give towards an order: nothing once it has
97
- # expired, been redeemed or been cancelled, and never less than zero,
98
- # since an admin can lower the amount below what is already in use.
98
+ # expired, been redeemed or been cancelled, and never less than zero.
99
99
  #
100
100
  # @return [BigDecimal]
101
101
  def spendable_amount
@@ -291,5 +291,17 @@ module Spree
291
291
  def set_currency
292
292
  self.currency ||= store&.default_currency
293
293
  end
294
+
295
+ # Once part of the card has been spent, its amount and currency are what
296
+ # that spending was measured against: changing either would invent a
297
+ # balance or leave a negative one. Keyed on the stored +amount_used+ and
298
+ # +amount_authorized+, so a workflow drawing the card down in the same
299
+ # save is unaffected.
300
+ def amount_and_currency_unchanged_once_used
301
+ return unless (amount_used_in_database.to_d + amount_authorized_in_database.to_d).positive?
302
+
303
+ errors.add(:amount, :cannot_change_once_used) if will_save_change_to_amount?
304
+ errors.add(:currency, :cannot_change_once_used) if will_save_change_to_currency?
305
+ end
294
306
  end
295
307
  end
@@ -108,7 +108,7 @@ module Spree
108
108
  end
109
109
  private_class_method :attached_blob_column
110
110
  self.whitelisted_ransackable_scopes = %w[attached unattached filename_cont]
111
- self.ransackable_scope_types = { 'attached' => 'boolean', 'unattached' => 'boolean' }
111
+ self.ransackable_scope_types = { 'attached' => 'boolean', 'unattached' => 'boolean', 'filename_cont' => 'text' }
112
112
 
113
113
  delegate :key, :attached?, :variant, :variable?, :blob, :filename, :variation, to: :attachment
114
114
 
@@ -53,6 +53,7 @@ module Spree
53
53
  # Magic methods
54
54
  #
55
55
  self.whitelisted_ransackable_scopes = %w[search_by_name]
56
+ self.ransackable_scope_types = { 'search_by_name' => 'text' }
56
57
  # `label` is what admin surfaces display, so it has to be filterable —
57
58
  # matching Spree::OptionValue, which already allows it.
58
59
  self.whitelisted_ransackable_attributes = %w[label name kind]
@@ -486,7 +486,9 @@ module Spree
486
486
  end
487
487
 
488
488
  def refunds_total
489
- read_association_in_memory?(:refunds) ? refunds.sum(0.to_d, &:amount) : refunds.sum(:amount)
489
+ return refunds.select(&:completed?).sum(0.to_d, &:amount) if read_association_in_memory?(:refunds)
490
+
491
+ refunds.completed_or_unset.sum(:amount)
490
492
  end
491
493
 
492
494
  # Checks if the order is partially refunded
@@ -494,6 +496,8 @@ module Spree
494
496
  def partially_refunded?
495
497
  return false if total_quantity.zero?
496
498
  return false if payment_state.in?(%w[void failed]) || refunds.empty?
499
+ # A refund only requested or failed has given nothing back yet.
500
+ return false unless refunds_total.positive?
497
501
 
498
502
  refunds_total < total_minus_store_credits - additional_tax_total.abs
499
503
  end
@@ -735,9 +739,11 @@ module Spree
735
739
  #
736
740
  # @return [BigDecimal]
737
741
  def returned_items_refund_total
738
- return refunds.select(&:for_returned_items?).sum(0.to_d, &:amount) if read_association_in_memory?(:refunds)
742
+ if read_association_in_memory?(:refunds)
743
+ return refunds.select { |refund| refund.for_returned_items? && refund.completed? }.sum(0.to_d, &:amount)
744
+ end
739
745
 
740
- refunds.for_returned_items.sum(:amount)
746
+ refunds.for_returned_items.completed_or_unset.sum(:amount)
741
747
  end
742
748
 
743
749
 
@@ -1314,7 +1320,7 @@ module Spree
1314
1320
  message: I18n.t('spree.cart_line_item.delivery_unavailable', li_name: line_item.name),
1315
1321
  line_item_id: line_item.prefixed_id,
1316
1322
  variant_id: line_item.variant&.prefixed_id
1317
- }
1323
+ }.compact
1318
1324
  end
1319
1325
  else
1320
1326
  errors.add(:base, :items_cannot_be_shipped, message: I18n.t('spree.items_cannot_be_shipped'))
@@ -230,7 +230,7 @@ module Spree
230
230
  def payment_total
231
231
  @payment_total ||= begin
232
232
  settled = payments.completed.to_a
233
- settled.sum(&:amount) - Spree::Refund.where(payment_id: settled.map(&:id)).sum(:amount)
233
+ settled.sum(&:amount) - Spree::Refund.completed_or_unset.where(payment_id: settled.map(&:id)).sum(:amount)
234
234
  end
235
235
  end
236
236
 
@@ -271,7 +271,7 @@ module Spree
271
271
  # @return [BigDecimal] what refunds for returns, claims and exchanges on
272
272
  # this checkout's payments have given back
273
273
  def returned_items_refund_total
274
- Spree::Refund.for_returned_items.where(payment_id: payments.completed.select(:id)).sum(:amount)
274
+ Spree::Refund.for_returned_items.completed_or_unset.where(payment_id: payments.completed.select(:id)).sum(:amount)
275
275
  end
276
276
 
277
277
  # @return [Boolean]
@@ -48,7 +48,8 @@ module Spree
48
48
  def order_settled_in_full?
49
49
  return false unless order.total.to_d.positive?
50
50
 
51
- settled = order.payments.completed.includes(:refunds).sum { |payment| payment.amount - payment.refunds.sum(:amount) }
51
+ completed = order.payments.completed
52
+ settled = completed.sum(:amount) - Spree::Refund.completed_or_unset.where(payment_id: completed.select(:id)).sum(:amount)
52
53
  settled >= order.total.to_d
53
54
  end
54
55
 
@@ -67,14 +67,16 @@ module Spree
67
67
  # @param captured [Boolean, nil] whether the gateway reports the funds
68
68
  # as captured. Callers who know the gateway state pass it; nil falls
69
69
  # back to when the payment method charges.
70
- def confirm!(captured: nil)
70
+ # @param capture_reference [String, nil] the provider's id for the
71
+ # capture, recorded so a late capture failure can find it
72
+ def confirm!(captured: nil, capture_reference: nil)
71
73
  captured = payment_method&.capture_at_checkout? if captured.nil?
72
74
 
73
75
  started_processing! if checkout?
74
76
 
75
77
  if captured && can_complete?
76
78
  complete!
77
- capture_events.create!(amount: amount)
79
+ capture_events.create!(amount: amount, status: 'completed', transaction_id: capture_reference)
78
80
  elsif can_pend?
79
81
  pend!
80
82
  end
@@ -85,12 +87,26 @@ module Spree
85
87
  # payment_method.cancel routes refunds through Refunds::Create. An
86
88
  # adapter that can void the payment outright does so either way.
87
89
  #
90
+ # A captured charge the gateway did not void keeps its completed status:
91
+ # the money was either refunded, which the refund records, or kept.
92
+ #
93
+ # A provider that answers +requested?+ settles later by webhook: an
94
+ # uncaptured payment waits on its void, and a completed one stays
95
+ # completed while the refund the gateway requested carries the outcome.
96
+ # So a gateway answers +requested?+ for a completed payment only after
97
+ # recording that refund (through Refunds::Create), or the outcome finds
98
+ # nothing to settle.
99
+ #
88
100
  # @param refund [Boolean] whether money already captured may be returned
89
101
  def cancel!(refund: true)
102
+ voids = payment_method.cancel_voids?(self)
90
103
  response = instrument_gateway_call(:cancel, payment_method) do
91
104
  payment_method.cancel(response_code, self, refund: refund)
92
105
  end
93
- handle_response(response, :void)
106
+ return handle_response(response, voids ? :void : :keep) unless response.success? && response.requested?
107
+ return true if completed?
108
+
109
+ request_void!
94
110
  end
95
111
 
96
112
  def gateway_options
@@ -122,6 +138,7 @@ module Spree
122
138
  when :complete then complete!
123
139
  when :pend then pend!
124
140
  when :void then void!
141
+ when :keep then nil
125
142
  else raise ArgumentError, "Unknown payment success state: #{success_state.inspect}"
126
143
  end
127
144
  else
@@ -19,7 +19,8 @@ module Spree
19
19
  include Spree::Payment::CustomEvents
20
20
 
21
21
  publishes_lifecycle_events
22
- publishes_events :captured, :completed, :paid, :refunded, :voided
22
+ publishes_events :captured, :completed, :paid, :refunded, :voided,
23
+ :capture_requested, :capture_failed, :void_requested, :void_failed
23
24
 
24
25
  NON_RISKY_AVS_CODES = ['B', 'D', 'H', 'J', 'M', 'Q', 'T', 'V', 'X', 'Y'].freeze
25
26
  RISKY_AVS_CODES = ['A', 'C', 'E', 'F', 'G', 'I', 'K', 'L', 'N', 'O', 'P', 'R', 'S', 'U', 'W', 'Z'].freeze
@@ -31,6 +32,9 @@ module Spree
31
32
  # method is consulted. Extend them to support gateways with other flows.
32
33
  VOIDABLE_STATUSES = %w[pending processing completed checkout].freeze
33
34
  CAPTURABLE_STATUSES = %w[checkout pending].freeze
35
+ # A payment settlement must leave alone: captured, or waiting on its
36
+ # provider's answer to a capture or void.
37
+ SETTLED_OR_WAITING_STATUSES = %w[completed requested].freeze
34
38
 
35
39
  with_options inverse_of: :payments do
36
40
  belongs_to :order, class_name: 'Spree::Order', touch: true, optional: true
@@ -125,7 +129,11 @@ module Spree
125
129
  # `invalid` status deliberately generates no predicate or scope: `invalid?`
126
130
  # is ActiveModel's, use +has_invalid_status?+.
127
131
  include Spree::HasStatus
128
- has_status :checkout, :processing, :pending, :completed, :failed, :void, :invalid,
132
+ # `requested` waits on the provider's webhook after it accepted a capture
133
+ # or void (a gateway answering `requested?`). It is in none of the
134
+ # claimable, voidable or capturable lists: nothing may start on the
135
+ # payment until the provider answers.
136
+ has_status :checkout, :processing, :pending, :requested, :completed, :failed, :void, :invalid,
129
137
  default: :checkout
130
138
 
131
139
  # Status writes, called from the payments workflows and Processing. The
@@ -205,6 +213,19 @@ module Spree
205
213
  true
206
214
  end
207
215
 
216
+ # The provider accepted a void and answers by webhook, which voids the
217
+ # payment then. A payment already void, or already waiting, is left as it
218
+ # is: a second request's late answer must not reopen it.
219
+ def request_void!
220
+ updates = { status: 'requested', updated_at: Time.current }
221
+ return false unless self.class.where(id: id).where.not(status: %w[void requested]).update_all(updates) == 1
222
+
223
+ assign_attributes(updates.except(:updated_at))
224
+ clear_attribute_changes(%i[status])
225
+ publish_event('payment.void_requested')
226
+ true
227
+ end
228
+
208
229
  def failure!
209
230
  update!(status: 'failed')
210
231
  end
@@ -238,6 +259,19 @@ module Spree
238
259
  (!payment_method.respond_to?(:can_capture?) || payment_method.can_capture?(self))
239
260
  end
240
261
 
262
+ # What the provider is still answering for a `requested` payment: a capture
263
+ # leaves a capture event waiting, a void leaves none.
264
+ #
265
+ # @return [String, nil] 'capture', 'void', or nil when nothing is requested
266
+ def requested_action
267
+ return unless requested?
268
+
269
+ # Read off the loaded rows when a list preloaded them, so serializing one
270
+ # costs no query per payment.
271
+ waiting = capture_events.loaded? ? capture_events.any?(&:requested?) : capture_events.requested.exists?
272
+ waiting ? 'capture' : 'void'
273
+ end
274
+
241
275
  # @deprecated read +status+ — removed in 6.3
242
276
  def state
243
277
  Spree::Deprecation.warn('Spree::Payment#state is deprecated and will be removed in Spree 6.3. Use #status instead.')
@@ -286,12 +320,58 @@ module Spree
286
320
  create_eligible_credit_event
287
321
  end
288
322
 
323
+ # Statuses a payment can be resized from: nobody has claimed it for the
324
+ # gateway yet, and it has not settled.
325
+ RESIZABLE_STATUSES = %w[checkout pending failed].freeze
326
+
327
+ # Shrinks this payment to +new_amount+ while nobody has claimed it. One
328
+ # conditional UPDATE, so a payment another run is charging (processing)
329
+ # or one that settled since the caller read it keeps the amount the
330
+ # gateway sees. An unsaved payment is resized in memory and saved with
331
+ # its claim. Store credit gets an eligibility event for the new amount,
332
+ # as {#update_store_credit_amount!} records one.
333
+ #
334
+ # @param new_amount [BigDecimal]
335
+ # @return [Boolean] false when the payment was claimed or completed meanwhile
336
+ def resize_if_unclaimed!(new_amount)
337
+ if new_record?
338
+ self.amount = new_amount
339
+ return true
340
+ end
341
+
342
+ resized = self.class.unscoped.where(id: id, status: RESIZABLE_STATUSES).
343
+ update_all(amount: new_amount, updated_at: Time.current)
344
+ return false if resized.zero?
345
+
346
+ self.amount = new_amount
347
+ clear_attribute_changes(%i[amount])
348
+ create_eligible_credit_event if store_credit?
349
+ true
350
+ end
351
+
352
+ # Voids this payment while nobody has claimed it. One conditional UPDATE,
353
+ # so a payment another run is charging (processing) is not overwritten
354
+ # and its capture can still be recorded. The caller publishes
355
+ # payment.voided, outside any lock it holds.
356
+ #
357
+ # @return [Boolean] false when the payment was claimed or settled meanwhile
358
+ def void_if_unclaimed!
359
+ voided = self.class.unscoped.where(id: id, status: RESIZABLE_STATUSES).
360
+ update_all(status: 'void', updated_at: Time.current)
361
+ return false if voided.zero?
362
+
363
+ self.status = 'void'
364
+ clear_attribute_changes(%i[status])
365
+ true
366
+ end
367
+
289
368
  def offsets_total
290
369
  offsets.sum(:amount)
291
370
  end
292
371
 
372
+ # A requested refund keeps its amount reserved until the provider answers.
293
373
  def credit_allowed
294
- amount - (offsets_total.abs + refunds.sum(:amount))
374
+ amount - (offsets_total.abs + refunds.not_failed.sum(:amount))
295
375
  end
296
376
 
297
377
  def can_credit?
@@ -366,29 +446,95 @@ module Spree
366
446
  end
367
447
 
368
448
  def captured_amount
369
- capture_events.sum(:amount)
449
+ capture_events.completed_or_unset.sum(:amount)
370
450
  end
371
451
 
372
452
  def uncaptured_amount
373
453
  amount - captured_amount
374
454
  end
375
455
 
456
+ # What the order still owes besides this payment: its total less what its
457
+ # other payments captured and, with +including_in_flight+, what they hold
458
+ # authorized. An order can carry several live payments, so this is the
459
+ # most any one of them may take. Read from the payment rows rather than
460
+ # the order's cached totals, which trail the payments settling.
461
+ #
462
+ # @param including_in_flight [Boolean] also count other pending and
463
+ # processing payments
464
+ # @param including_processing [Boolean] also count other processing
465
+ # payments — the ones being charged at the gateway right now
466
+ # @return [BigDecimal, nil] nil for a payment not made against an order
467
+ def amount_owed_by_order(including_in_flight:, including_processing: false)
468
+ return if order_id.nil?
469
+
470
+ fresh_order = Spree::Order.find(order_id)
471
+ return BigDecimal('0') if fresh_order.canceled?
472
+
473
+ others = fresh_order.payments.where.not(id: id)
474
+ by_status, awaiting = sibling_amounts(others)
475
+ captured = others.where(status: 'completed')
476
+ owed = fresh_order.total - by_status.fetch('completed', 0) - awaiting +
477
+ Spree::Refund.where(payment_id: captured.select(:id)).sum(:amount) - fresh_order.returned_items_refund_total
478
+ if including_in_flight
479
+ owed -= by_status.fetch('pending', 0) + by_status.fetch('processing', 0)
480
+ elsif including_processing
481
+ owed -= by_status.fetch('processing', 0)
482
+ end
483
+
484
+ [owed, BigDecimal('0')].max
485
+ end
486
+
487
+ # Sizes a remainder split off a partial capture to what its order still
488
+ # owes beyond its other live payments: voids it when nothing is, so the
489
+ # hold on the customer's money is released, and shrinks it when less is.
490
+ #
491
+ # Read and resized under the order's lock, which a capture holds while it
492
+ # moves a sibling from processing to requested and a dispatch holds while
493
+ # it claims a payment: the owed figure cannot count a sibling twice, and a
494
+ # remainder another run claimed meanwhile keeps the amount it was claimed at.
495
+ #
496
+ # @return [Boolean] whether the remainder still needs authorizing
497
+ def trim_remainder_to_amount_owed!
498
+ voided = false
499
+ outcome = with_order_lock do
500
+ owed = amount_owed_by_order(including_in_flight: true)
501
+ if owed&.zero?
502
+ voided = void_if_unclaimed!
503
+ next :released
504
+ end
505
+ next :authorize if owed.nil? || owed >= amount || resize_if_unclaimed!(owed)
506
+
507
+ :claimed
508
+ end
509
+ publish_event('payment.voided') if voided
510
+ outcome == :authorize
511
+ end
512
+
376
513
  # Row work only — moves the uncaptured remainder onto a new pending
377
514
  # payment and shrinks this one to what was captured. The caller authorizes
378
515
  # the returned remainder at the gateway afterwards, outside any lock.
379
516
  #
380
- # @return [Spree::Payment, nil] the remainder payment, or nil when fully captured
517
+ # @return [Spree::Payment, nil] the remainder payment, or nil when fully
518
+ # captured or when the order can take no more
381
519
  def split_uncaptured_amount
382
520
  return if uncaptured_amount <= 0
383
521
 
384
- remainder = owner.payments.create!(
522
+ remainder = owner.payments.new(
385
523
  amount: uncaptured_amount,
386
524
  payment_method: payment_method,
387
525
  source: source,
388
526
  status: 'pending',
389
527
  capture_on_dispatch: true
390
528
  )
391
- carry_splits_to(remainder)
529
+ # The order may now take less than the authorization left over, when its
530
+ # total came down after the payment was authorized.
531
+ remainder.amount = [remainder.amount, remainder.max_amount].min unless grouped?
532
+ if remainder.amount.positive?
533
+ remainder.save!
534
+ carry_splits_to(remainder)
535
+ else
536
+ remainder = nil
537
+ end
392
538
  # Bang: a silent failure here would leave this payment at its full amount
393
539
  # beside a remainder that also exists, so the group would hold more money
394
540
  # than the customer was ever charged.
@@ -544,6 +690,34 @@ module Spree
544
690
  self.amount = owner.total - owner.payment_total
545
691
  end
546
692
 
693
+ # One statement for every sum, so a sibling moving between statuses
694
+ # between two reads is counted once: not dropped from both the completed
695
+ # and the in-flight sums, nor counted both as in flight (processing) and
696
+ # as awaiting its provider (requested).
697
+ #
698
+ # @return [Array(Hash{String => BigDecimal}, BigDecimal)] the amounts by
699
+ # status, and the captures sent to a provider that confirms them by
700
+ # webhook, which count as collected already
701
+ def sibling_amounts(others)
702
+ events = Spree::PaymentCaptureEvent.arel_table
703
+ awaiting_sql = events.project(events[:amount].sum).
704
+ where(events[:payment_id].eq(Spree::Payment.arel_table[:id]).and(events[:status].eq('requested')))
705
+ rows = others.where(status: %w[completed pending processing requested]).
706
+ pluck(:status, :amount, Arel::Nodes::Grouping.new(awaiting_sql))
707
+
708
+ by_status = Hash.new(BigDecimal('0'))
709
+ awaiting = BigDecimal('0')
710
+ rows.each do |status, amount, requested|
711
+ by_status[status] += amount unless status == 'requested'
712
+ awaiting += BigDecimal(requested.to_s) if requested
713
+ end
714
+ [by_status, awaiting]
715
+ end
716
+
717
+ def with_order_lock(&)
718
+ order_id ? Spree::Order.find(order_id).with_lock(&) : yield
719
+ end
720
+
547
721
  def amount_must_be_less_than_or_equal_to_max_amount
548
722
  errors.add(:amount, :greater_than_max_amount, max_amount: max_amount) if amount > max_amount
549
723
  end
@@ -603,9 +777,14 @@ module Spree
603
777
  action_authorization_code: response_code)
604
778
  end
605
779
 
780
+ # A buyer who picks another way to pay at checkout replaces the attempt
781
+ # they started, so a cart keeps one live payment. An order is paid from
782
+ # the back office, where each payment recorded is money the merchant
783
+ # means to collect alongside the others.
606
784
  def invalidate_old_payments
607
785
  # invalid payment or store_credit payment shouldn't invalidate other payment types
608
786
  return if has_invalid_status? || store_credit?
787
+ return unless owner.is_a?(Spree::Cart)
609
788
 
610
789
  owner.payments.with_state('checkout').where.not(id: id).each do |payment|
611
790
  payment.invalidate! unless payment.store_credit?
@@ -2,6 +2,8 @@ module Spree
2
2
  class PaymentCaptureEvent < Spree.base_class
3
3
  has_prefix_id :pce
4
4
 
5
+ include Spree::SettlementStatus
6
+
5
7
  belongs_to :payment, class_name: 'Spree::Payment'
6
8
 
7
9
  delegate :currency, to: :payment
@@ -86,6 +86,12 @@ module Spree
86
86
  handle_action(action, :credit, auth_code)
87
87
  end
88
88
 
89
+ # Cancelling gives the credit back, so the payment is void even when it
90
+ # was captured.
91
+ def cancel_voids?(_payment)
92
+ true
93
+ end
94
+
89
95
  # Credit goes back to the customer's balance rather than a card, so this
90
96
  # is a release rather than a refund and `refund:` does not apply.
91
97
  def cancel(auth_code, _payment = nil, refund: true)