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
@@ -14,36 +14,34 @@ module Spree
14
14
  # order's payment status is derived from: an order that still read as
15
15
  # unpaid until a job ran would be showing the wrong thing to the merchant
16
16
  # and to the seller.
17
+ #
18
+ # A share's refunded amount moves when a refund completes (payment.refunded,
19
+ # whether the provider answered at once or by webhook) or fails after it
20
+ # completed (refund.failed), never when the row is created: a provider may
21
+ # still refuse a requested refund.
17
22
  class PaymentSplitSubscriber < Spree::Subscriber
18
- subscribes_to 'refund.created', 'payment.completed', async: false
23
+ subscribes_to 'payment.refunded', 'refund.failed', 'payment.completed', async: false
19
24
 
20
- on 'refund.created', :handle_refund
25
+ on 'payment.refunded', :handle_refund
26
+ on 'refund.failed', :handle_refund_failed
21
27
  on 'payment.completed', :handle_capture
22
28
 
29
+ # The payload names the payment, not the refund, so every share of it is
30
+ # recomputed; each is derived from the rows, so the others do not move.
23
31
  def handle_refund(event)
24
- refund = Spree::Refund.find_by_prefix_id(event.payload['id'])
25
- return unless refund
32
+ payment = Spree::Payment.find_by_prefix_id(event.payload['id'])
33
+ return if payment.nil? || !payment.grouped?
34
+
35
+ payment.payment_splits.includes(:order).find_each { |split| refresh_refunded_amount(split) }
36
+ end
26
37
 
27
- order = refund.order
38
+ def handle_refund_failed(event)
39
+ refund = Spree::Refund.find_by_prefix_id(event.payload['id'])
40
+ order = refund&.order
28
41
  return if order.nil? || !order.grouped?
29
42
 
30
43
  split = order.payment_split_for(refund.payment)
31
- return if split.nil?
32
-
33
- # Recomputed from the refunds rather than incremented, so a replayed
34
- # event cannot count the same money twice — and read and written under
35
- # the row's lock, so two refunds landing together cannot each total the
36
- # rows before the other's has committed.
37
- split.with_lock do
38
- refunded = Spree::Refund.where(payment_id: refund.payment_id, order_id: order.id).sum(:amount)
39
- split.update!(refunded_amount: refunded)
40
- end
41
-
42
- # Deliberately re-derived here even though OrderStatusSubscriber also
43
- # answers refund.created: subscriber order is not guaranteed, and a
44
- # status derived before this share was written would describe the refund
45
- # as not having happened.
46
- Spree::Orders::UpdateStatuses.call(order: order)
44
+ refresh_refunded_amount(split) if split
47
45
  end
48
46
 
49
47
  # The whole payment settled, so every share it covers is captured in full.
@@ -67,5 +65,25 @@ module Spree
67
65
  Spree::Orders::UpdateStatuses.call(order: split.order) if settled && split.order
68
66
  end
69
67
  end
68
+
69
+ private
70
+
71
+ def refresh_refunded_amount(split)
72
+ order = split.order
73
+ # Recomputed from the completed refunds rather than incremented, so a
74
+ # replayed event cannot count the same money twice — and read and
75
+ # written under the row's lock, so two refunds landing together cannot
76
+ # each total the rows before the other's has committed.
77
+ split.with_lock do
78
+ refunded = Spree::Refund.completed_or_unset.where(payment_id: split.payment_id, order_id: split.order_id).sum(:amount)
79
+ split.update!(refunded_amount: refunded)
80
+ end
81
+
82
+ # Deliberately re-derived here even though OrderStatusSubscriber also
83
+ # answers these events: subscriber order is not guaranteed, and a status
84
+ # derived before this share was written would describe the refund as
85
+ # not having happened.
86
+ Spree::Orders::UpdateStatuses.call(order: order) if order
87
+ end
70
88
  end
71
89
  end
@@ -3,24 +3,36 @@
3
3
  module Spree
4
4
  # Takes back part of a seller's earning when their order is refunded.
5
5
  #
6
- # Hangs off `refund.created` rather than off returns, exchanges or claims
6
+ # Hangs off refunds rather than off returns, exchanges or claims
7
7
  # individually: every one of those funnels its money movement through a
8
8
  # refund, so one listener covers all three.
9
9
  #
10
+ # Only money that went back is taken from the seller. A refund whose
11
+ # provider answers later is created requested, so it is reversed when it
12
+ # completes: payment.refunded names that refund in its metadata. The
13
+ # workflow is keyed on the refund, so hearing a refund twice reverses it once.
14
+ #
10
15
  # A refund on an order that never shipped reverses nothing, because nothing
11
16
  # was credited — the workflow answers that case by doing nothing rather than
12
17
  # by failing.
13
18
  class SellerTransferReversalSubscriber < Spree::Subscriber
14
- subscribes_to 'refund.created'
19
+ subscribes_to 'refund.created', 'payment.refunded'
15
20
 
16
21
  def handle(event)
17
- refund = Spree::Refund.find_by_prefix_id(event.payload['id'])
18
- return unless refund
22
+ refunds_for(event).each do |refund|
23
+ order = refund.order
24
+ next if order.nil? || order.seller_id.blank?
25
+
26
+ Spree.seller_transfer_reverse_workflow.call(order: order, amount: refund.amount, refund: refund)
27
+ end
28
+ end
19
29
 
20
- order = refund.order
21
- return if order.nil? || order.seller_id.blank?
30
+ private
22
31
 
23
- Spree.seller_transfer_reverse_workflow.call(order: order, amount: refund.amount, refund: refund)
32
+ def refunds_for(event)
33
+ refund_id = event.name == 'payment.refunded' ? event.metadata['refund_id'] : event.payload['id']
34
+ refund = Spree::Refund.find_by_prefix_id(refund_id) if refund_id.present?
35
+ refund&.completed? ? [refund] : []
24
36
  end
25
37
  end
26
38
  end
@@ -13,12 +13,16 @@ module Spree
13
13
 
14
14
  param :metrics, type: :array, items: :string,
15
15
  description: 'Metric names, e.g. ["orders", "net_sales"]', required: true
16
- param :dimensions, type: :array, items: :string,
16
+ param :dimensions, type: :array, items: %i[string object],
17
17
  description: 'Dimensions to group by, as named by describe_reporting ' \
18
- '(e.g. ["completed_at", "channel"]). Omit for a single total.',
18
+ '(e.g. ["completed_at", "channel"]). A date dimension takes a grain as ' \
19
+ '{"name": "completed_at", "grain": "month"} (hour, day, week or month); ' \
20
+ 'without one, the grain is picked to fit the time range. Omit for a single total.',
19
21
  required: false
20
22
  param :time_range, type: :object,
21
- description: 'A preset such as {"preset": "last_30_days"}, or {"from": "2026-01-01", "to": "2026-03-31"}',
23
+ description: 'A preset such as {"preset": "last_30_days"} or {"preset": "year_to_date"}, ' \
24
+ 'or dates as {"since": "2026-01-01", "until": "2026-03-31"}. ' \
25
+ 'Defaults to the last 30 days.',
22
26
  required: false
23
27
  param :filters, type: :array, items: :object,
24
28
  description: 'Dimension filters, each {"dimension": …, "op": "eq" or "in", "value": …} — ' \
@@ -32,15 +36,38 @@ module Spree
32
36
  # returned thousands is capped rather than truncated silently.
33
37
  DEFAULT_LIMIT = 50
34
38
  MAX_LIMIT = 500
39
+ # A date dimension given without a grain gets the finest one that keeps
40
+ # the series about this long: a month by day, a quarter by week, a year
41
+ # by month. The reporting default, hour, fits almost no question.
42
+ TARGET_POINTS = 31
43
+ # Models often write a range as from/to; both are read as since/until.
44
+ TIME_RANGE_ALIASES = { 'from' => 'since', 'to' => 'until' }.freeze
45
+ TIME_RANGE_KEYS = %w[preset since until].freeze
35
46
 
36
47
  def call(metrics:, dimensions: nil, time_range: nil, filters: nil, sort: nil, limit: nil, currency: nil)
37
- query = build_query(metrics: metrics, dimensions: dimensions, time_range: time_range,
38
- filters: filters, sort: sort, limit: limit, currency: currency)
48
+ row_limit = [(limit || DEFAULT_LIMIT).to_i, MAX_LIMIT].min
49
+ raise Spree::Reporting::InvalidQuery, "limit must be between 1 and #{MAX_LIMIT}" if row_limit < 1
50
+
51
+ # An unsorted date series is reported whole or not at all: cut at the
52
+ # limit, it would end early next to totals for the whole range. A
53
+ # sorted one ("the five best days") is a ranking, cut on purpose.
54
+ dimensions = Array(dimensions).map { |entry| entry.is_a?(Hash) ? entry.stringify_keys : entry }
55
+ series = sort.blank? && dimensions.any? { |entry| time_dimension_for(entry) }
56
+
57
+ query = build_query(metrics: metrics, dimensions: dimensions, time_range: time_range, filters: filters,
58
+ sort: sort, currency: currency, limit: (row_limit unless series),
59
+ target_points: series && dimensions.one? ? [TARGET_POINTS, row_limit].min : TARGET_POINTS)
39
60
 
40
61
  refusal = unauthorized_members(query)
41
62
  return refusal if refusal
42
63
 
43
- shape(query.execute)
64
+ result = query.execute
65
+ if series && Array(result.rows).size > row_limit
66
+ return { error: "This report has #{result.rows.size} rows, more than the limit of #{row_limit}. " \
67
+ "Shorten the range, use a coarser grain, or raise limit (up to #{MAX_LIMIT})." }
68
+ end
69
+
70
+ shape(result)
44
71
  rescue Spree::Reporting::UnknownMember => e
45
72
  { error: e.message, valid: Array(e.valid).map(&:to_s) }
46
73
  rescue Spree::Reporting::InvalidQuery => e
@@ -56,20 +83,95 @@ module Spree
56
83
 
57
84
  private
58
85
 
59
- def build_query(metrics:, dimensions:, time_range:, filters:, sort:, limit:, currency:)
60
- parameters = {
61
- 'metrics' => Array(metrics),
62
- 'dimensions' => Array(dimensions),
63
- 'filters' => Array(filters),
64
- 'limit' => [(limit || DEFAULT_LIMIT).to_i, MAX_LIMIT].min
65
- }
66
- parameters['time_range'] = time_range if time_range.present?
86
+ def build_query(metrics:, dimensions:, time_range:, filters:, sort:, currency:, limit:, target_points:)
87
+ parameters = { 'metrics' => Array(metrics), 'filters' => Array(filters) }
88
+ parameters['limit'] = limit if limit
89
+ parameters['time_range'] = normalize_time_range(time_range) if time_range.present?
67
90
  parameters['sort'] = sort if sort.present?
68
91
  parameters['currency'] = currency if currency.present?
69
92
 
93
+ ungrained = dimensions.index { |entry| ungrained_time_dimension(entry) }
94
+ return reporting_query(parameters.merge('dimensions' => dimensions)) if ungrained.nil?
95
+
96
+ # The range decides the grain, and only the query resolves the range
97
+ # (presets, the store's timezone), so it is built once at the coarsest
98
+ # grain to read the range back, then again at the grain that fits.
99
+ entry = dimensions[ungrained]
100
+ dimension = ungrained_time_dimension(entry)
101
+ entry = { 'name' => entry } unless entry.is_a?(Hash)
102
+ draft = dimensions.dup
103
+ draft[ungrained] = entry.merge('grain' => dimension.grains.last.to_s)
104
+ query = reporting_query(parameters.merge('dimensions' => draft))
105
+
106
+ draft[ungrained] = entry.merge('grain' => fitting_grain(dimension, query, target_points).to_s)
107
+ reporting_query(parameters.merge('dimensions' => draft))
108
+ end
109
+
110
+ def reporting_query(parameters)
70
111
  Spree::Reporting::Query.new(store: context.store, params: parameters)
71
112
  end
72
113
 
114
+ # The registry's time dimension an entry names, or nil. Anything else is
115
+ # left for the query to accept or refuse.
116
+ def time_dimension_for(entry)
117
+ name = entry.is_a?(Hash) ? entry['name'] : entry
118
+ return unless name.is_a?(String) || name.is_a?(Symbol)
119
+
120
+ dimension = Spree.reporting.dimensions[name.to_sym]
121
+ dimension if dimension&.time?
122
+ end
123
+
124
+ def ungrained_time_dimension(entry)
125
+ return if entry.is_a?(Hash) && ['', nil].exclude?(entry['grain'])
126
+
127
+ time_dimension_for(entry)
128
+ end
129
+
130
+ def fitting_grain(dimension, query, target_points)
131
+ dimension.grains.find { |grain| (bucket_count(query, grain) || Float::INFINITY) <= target_points } ||
132
+ dimension.grains.last
133
+ end
134
+
135
+ # Counted on the store's calendar, as the adapter buckets them, so a
136
+ # daylight saving change does not push 31 days over the target.
137
+ def bucket_count(query, grain)
138
+ first = query.time_range.first.in_time_zone(query.time_zone)
139
+ last = query.time_range.last.in_time_zone(query.time_zone)
140
+
141
+ case grain
142
+ when :hour then ((last - first.beginning_of_hour) / 1.hour).floor + 1
143
+ when :day then (last.to_date - first.to_date).to_i + 1
144
+ when :week then ((last.to_date.beginning_of_week(:monday) - first.to_date.beginning_of_week(:monday)).to_i / 7) + 1
145
+ when :month then ((last.year * 12) + last.month) - ((first.year * 12) + first.month) + 1
146
+ end
147
+ end
148
+
149
+ # A range in a shape the query does not read would be dropped there for
150
+ # the last 30 days, and the model would report on the wrong period.
151
+ def normalize_time_range(range)
152
+ return range unless range.is_a?(Hash)
153
+
154
+ range = range.to_h.stringify_keys
155
+ TIME_RANGE_ALIASES.each do |alias_key, key|
156
+ next unless range.key?(alias_key)
157
+ raise Spree::Reporting::InvalidQuery, "time_range takes #{alias_key} or #{key}, not both" if range.key?(key)
158
+
159
+ range[key] = range.delete(alias_key)
160
+ end
161
+
162
+ if range.key?('preset') && range.keys.intersect?(%w[since until])
163
+ raise Spree::Reporting::InvalidQuery, 'time_range takes a preset or since and until, not both'
164
+ end
165
+
166
+ unknown = range.keys - TIME_RANGE_KEYS
167
+ if unknown.any?
168
+ raise Spree::Reporting::InvalidQuery,
169
+ "time_range does not take #{unknown.join(', ')}. Use {\"preset\": …} or {\"since\": …, \"until\": …}."
170
+ end
171
+
172
+ range
173
+ end
174
+
73
175
  # The same per-member check the reporting endpoint makes, in the same
74
176
  # two flavours: a key is checked against its scopes, an admin against
75
177
  # their ability. A caller who may read orders but not products cannot
@@ -295,7 +295,7 @@ module Spree
295
295
  copy_promotions!(cart, order)
296
296
  copy_tax_identifier!(cart, order)
297
297
  copy_tax_exemptions!(cart, order, line_item_map, fulfillment_map, fee_map)
298
- copy_po_document!(cart, order)
298
+ order.copy_po_document_from!(cart)
299
299
  repoint_money_records!(cart, order)
300
300
  Spree.cart_copiers.each { |copier| copier.call(cart: cart, order: order, line_item_map: line_item_map) }
301
301
 
@@ -403,24 +403,6 @@ module Spree
403
403
  )
404
404
  end
405
405
 
406
- # The buyer's purchase order follows the number onto the order. The same
407
- # blob is attached to both records rather than uploaded twice — the cart
408
- # keeps its copy so a completion that rolls back leaves the buyer's
409
- # upload where they left it.
410
- #
411
- # The order is persisted and unchanged here, so `attach` saves
412
- # immediately and answers nil instead of raising when the save is
413
- # refused. Left unchecked the placed order would simply have no
414
- # paperwork, silently — so the failure is raised into the completion
415
- # transaction rather than dropped.
416
- def copy_po_document!(cart, order)
417
- return unless cart.po_document.attached?
418
-
419
- return if order.po_document.attach(cart.po_document.blob)
420
-
421
- raise ActiveRecord::RecordInvalid, order
422
- end
423
-
424
406
  # Which link of the chain produced the snapshot, so a placed order's tax
425
407
  # treatment names its own reason.
426
408
  def source_of(resolved)
@@ -143,9 +143,9 @@ module Spree
143
143
  return cart.payment_splits.reload.to_a.sum(&:net_captured_amount)
144
144
  end
145
145
 
146
- cart.payments.completed.includes(:refunds).inject(0) do |sum, payment|
147
- sum + payment.amount - payment.refunds.sum(:amount)
148
- end
146
+ # Loaded once, so refunds are subtracted for exactly the payments summed.
147
+ completed = cart.payments.completed.to_a
148
+ completed.sum(0.to_d, &:amount) - Spree::Refund.completed_or_unset.where(payment_id: completed.map(&:id)).sum(:amount)
149
149
  end
150
150
 
151
151
  def refresh_grand_total
@@ -55,6 +55,11 @@ module Spree
55
55
  @amount_to_refund ||= amount_paid if refund_payments
56
56
 
57
57
  ApplicationRecord.transaction do
58
+ # The row lock a capture takes to record its answer, so a capture
59
+ # cannot be recorded between this check and the cancel. Taken by
60
+ # query: the order may carry figures not yet saved.
61
+ Spree::Order.lock.find(order.id)
62
+ step :ensure_no_payment_in_flight
58
63
  step :mark_canceled
59
64
  step :cancel_fulfillments
60
65
  run_hooks :after_cancel
@@ -92,6 +97,20 @@ module Spree
92
97
  failure(order)
93
98
  end
94
99
 
100
+ # Voiding a payment whose capture or void is in flight, or that the
101
+ # provider is still answering, would release a hold it may be capturing.
102
+ def ensure_no_payment_in_flight
103
+ payments = if order.grouped?
104
+ Spree::Payment.where(id: order.payment_splits.select(:payment_id))
105
+ else
106
+ order.payments
107
+ end
108
+ return unless payments.with_status(:processing, :requested).exists?
109
+
110
+ order.errors.add(:base, :payment_requested, message: I18n.t('spree.payment_requested_awaiting_provider'))
111
+ failure(order)
112
+ end
113
+
95
114
  # A reason from another store would label this order with a vocabulary
96
115
  # its merchant never wrote — the same scoping rule the controllers apply
97
116
  # to every incidental id, enforced here so console and extension callers
@@ -305,9 +305,15 @@ module Spree
305
305
  failure(order, result.error) if result.failure?
306
306
  end
307
307
 
308
+ # Net of refunds on captured payments, as Payment#amount_owed_by_order
309
+ # counts them: money given back is owed again, except what a return
310
+ # refunded, since those goods came back too.
308
311
  def payment_covered?
309
312
  order.payments.reset
310
- order.payments.valid.where(status: %w[pending processing completed]).sum(:amount) >= order.amount_due_at_checkout
313
+ live = order.payments.valid.where(status: %w[pending processing completed])
314
+ refunded = Spree::Refund.where(payment_id: order.payments.where(status: 'completed').select(:id)).sum(:amount) -
315
+ order.returned_items_refund_total
316
+ live.sum(:amount) - refunded >= order.amount_due_at_checkout
311
317
  end
312
318
  end
313
319
  end
@@ -20,10 +20,12 @@ module Spree
20
20
  # the pre-6.0 contract (deprecated, removed in 6.5).
21
21
  def perform(payment:, amount: nil)
22
22
  super
23
+ @amount_requested = !amount.nil?
23
24
  @amount = capture_amount(amount)
24
25
 
25
26
  step :ensure_capturable
26
27
  step :ensure_within_payment_amount
28
+ step :ensure_within_amount_owed
27
29
  # Veto point — fraud holds, manual review. Before any money moves.
28
30
  run_hooks :validate
29
31
  run_hooks :before_capture
@@ -39,7 +41,9 @@ module Spree
39
41
  external_step :authorize_remainder
40
42
 
41
43
  run_hooks :after_capture
42
- payment.publish_event('payment.captured')
44
+ # A requested capture is confirmed by the provider's webhook, which
45
+ # publishes payment.captured then.
46
+ payment.publish_event(response.requested? ? 'payment.capture_requested' : 'payment.captured')
43
47
  success(payment.reload)
44
48
  end
45
49
 
@@ -65,6 +69,7 @@ module Spree
65
69
  # this workflow again.
66
70
  def ensure_capturable
67
71
  halt!(payment) if payment.completed?
72
+ failure(payment, I18n.t('spree.payment_requested_awaiting_provider')) if payment.requested?
68
73
  return if payment.pending? || payment.checkout? || payment.processing? || payment.failed?
69
74
 
70
75
  failure(payment, :payment_not_capturable)
@@ -81,12 +86,91 @@ module Spree
81
86
  failure(payment, :capture_exceeds_payment_amount)
82
87
  end
83
88
 
89
+ # Other payments on the order may have captured some of its total
90
+ # already, or the order total may have dropped since this payment was
91
+ # authorized; this one may take only what is left owing.
92
+ def ensure_within_amount_owed
93
+ # Another request may have captured this payment since it was loaded:
94
+ # that is a success, whatever is owed now.
95
+ halt!(payment) if refresh_from_row == 'completed'
96
+
97
+ limit_to_amount_owed(payment.amount_owed_by_order(including_in_flight: false))
98
+ end
99
+
100
+ # The owed check again, under the order's row lock and together with
101
+ # the claim. A payment being charged sits in processing until it is
102
+ # recorded, and here it counts as taken: of two captures racing on one
103
+ # order, the second reads after the first has claimed, so both cannot
104
+ # pass a check made before either moved money.
105
+ #
106
+ # The row is read again here, with its amount: a processing run may have
107
+ # resized this payment since it was loaded, and the claim reserves the
108
+ # row's amount, so the capture must not take more than that.
84
109
  def claim
85
- halt!(payment) unless payment.started_processing!
110
+ outcome = with_order_lock do
111
+ next false if refresh_from_row == 'completed'
112
+
113
+ refusal = amount_within_payment_refusal ||
114
+ amount_owed_refusal(payment.amount_owed_by_order(including_in_flight: false, including_processing: true))
115
+ next refusal if refusal
116
+
117
+ payment.started_processing!
118
+ end
119
+ failure(payment, outcome) if outcome.is_a?(String)
120
+ halt!(payment) unless outcome
86
121
  rescue Spree::Core::GatewayError => error
87
122
  failure(payment, error.message)
88
123
  end
89
124
 
125
+ # Reads the status and amount another run may have written since this
126
+ # instance was loaded. Deliberately not a reload, which would discard the
127
+ # in-memory source (card numbers never persist).
128
+ def refresh_from_row
129
+ return payment.status unless payment.persisted?
130
+
131
+ status, amount = Spree::Payment.unscoped.where(id: payment.id).pick(:status, :amount)
132
+ payment.amount = amount
133
+ payment.clear_attribute_changes(%i[amount])
134
+ status
135
+ end
136
+
137
+ # The payment's own amount may have shrunk since the early check. An
138
+ # amount the caller asked for is then refused; with none asked for, the
139
+ # capture shrinks with it.
140
+ def amount_within_payment_refusal
141
+ return if @amount <= payment.amount
142
+ return I18n.t('spree.capture_exceeds_payment_amount') if @amount_requested
143
+
144
+ @amount = payment.amount
145
+ nil
146
+ end
147
+
148
+ def limit_to_amount_owed(owed)
149
+ refusal = amount_owed_refusal(owed)
150
+ failure(payment, refusal) if refusal
151
+ end
152
+
153
+ # An amount the caller asked for is refused when it exceeds what is
154
+ # owed. With no amount asked for — the dashboard's capture — the capture
155
+ # shrinks to what is owed, and record_capture splits off the rest of the
156
+ # authorization, which authorize_remainder then releases. Returns the
157
+ # refusal message, or nil.
158
+ def amount_owed_refusal(owed)
159
+ return if owed.nil? || @amount <= owed
160
+ return I18n.t('spree.order_payment_already_covered') if !@amount_requested && !owed.positive?
161
+
162
+ unless @amount_requested
163
+ @amount = owed
164
+ return
165
+ end
166
+
167
+ I18n.t('spree.capture_exceeds_amount_owed', amount: Spree::Money.new(owed, currency: payment.currency).to_s)
168
+ end
169
+
170
+ def with_order_lock(&)
171
+ payment.order_id ? payment.owner.with_lock(&) : yield
172
+ end
173
+
90
174
  def capture_at_gateway
91
175
  @response = payment.protect_from_connection_error do
92
176
  instrument_gateway_call(:capture, payment.payment_method) do
@@ -106,14 +190,21 @@ module Spree
106
190
  # Locked because the webhook settling the same payment races this
107
191
  # request. The DB recheck — deliberately not a reload, which would
108
192
  # discard the in-memory source (card numbers never persist) — makes
109
- # the capture event exactly-once.
193
+ # the capture event exactly-once: a payment no longer `processing` was
194
+ # moved by settlement, a provider outcome or another capture, and is
195
+ # not reopened.
110
196
  def record_capture
111
197
  already_captured = false
112
198
  payment.owner.with_lock do
113
- if Spree::Payment.where(id: payment.id, status: 'completed').exists?
199
+ if Spree::Payment.where(id: payment.id).where.not(status: 'processing').exists?
114
200
  already_captured = true
201
+ elsif response.requested?
202
+ # The provider accepted the capture and answers by webhook: no
203
+ # remainder and no completion until it does.
204
+ payment.capture_events.create!(amount: @amount, status: 'requested', transaction_id: response.reference)
205
+ payment.update!(status: 'requested')
115
206
  else
116
- payment.capture_events.create!(amount: @amount)
207
+ payment.capture_events.create!(amount: @amount, status: 'completed')
117
208
  # Split before completing, so payment.completed publishes with
118
209
  # the captured amount and the order recomputes from correct rows.
119
210
  @remainder = payment.split_uncaptured_amount
@@ -127,6 +218,9 @@ module Spree
127
218
  # outside the lock.
128
219
  def authorize_remainder
129
220
  return if remainder.blank?
221
+ # Holding more than the order still owes would only keep the
222
+ # customer's money tied up.
223
+ return unless remainder.trim_remainder_to_amount_owed!
130
224
 
131
225
  result = Spree.payment_process_workflow.call(payment: remainder, action: :authorize)
132
226
  failure(remainder, result.error.value.to_s) if result.failure?