spree_core 6.0.6 → 6.0.7

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 (105) hide show
  1. checksums.yaml +4 -4
  2. data/app/jobs/spree/base_job.rb +9 -5
  3. data/app/jobs/spree/gift_cards/bulk_generate_job.rb +4 -2
  4. data/app/jobs/spree/gift_cards/publish_created_events_job.rb +46 -0
  5. data/app/jobs/spree/images/save_from_url_job.rb +92 -22
  6. data/app/jobs/spree/payments/handle_webhook_job.rb +107 -1
  7. data/app/mailers/spree/api_key_mailer.rb +52 -0
  8. data/app/models/concerns/spree/prefixed_id.rb +12 -6
  9. data/app/models/concerns/spree/purchase/lifecycle.rb +4 -1
  10. data/app/models/concerns/spree/purchase/market.rb +2 -2
  11. data/app/models/concerns/spree/purchase/warnings.rb +29 -0
  12. data/app/models/concerns/spree/user_address.rb +4 -2
  13. data/app/models/concerns/spree/user_management.rb +26 -2
  14. data/app/models/spree/api_key.rb +24 -0
  15. data/app/models/spree/base.rb +29 -0
  16. data/app/models/spree/cart.rb +90 -9
  17. data/app/models/spree/channel.rb +2 -1
  18. data/app/models/spree/country.rb +9 -0
  19. data/app/models/spree/credit_card.rb +2 -0
  20. data/app/models/spree/delivery_origin_group.rb +2 -1
  21. data/app/models/spree/export.rb +10 -0
  22. data/app/models/spree/exports/report.rb +16 -0
  23. data/app/models/spree/fulfillment.rb +30 -0
  24. data/app/models/spree/fulfillment_group.rb +13 -0
  25. data/app/models/spree/gift_card.rb +27 -3
  26. data/app/models/spree/gift_card_batch.rb +82 -11
  27. data/app/models/spree/invitation.rb +51 -7
  28. data/app/models/spree/market.rb +6 -1
  29. data/app/models/spree/media.rb +30 -3
  30. data/app/models/spree/oauth_access_token.rb +2 -0
  31. data/app/models/spree/order.rb +4 -4
  32. data/app/models/spree/payment_session.rb +21 -1
  33. data/app/models/spree/price_history.rb +2 -0
  34. data/app/models/spree/promotion.rb +6 -2
  35. data/app/models/spree/tax_provider/base.rb +29 -0
  36. data/app/serializers/spree/emails/api_key_serializer.rb +16 -0
  37. data/app/services/spree/orders/update.rb +32 -2
  38. data/app/validators/spree/attachment_content_type_validator.rb +29 -3
  39. data/app/views/spree/api_key_mailer/secret_key_created.liquid +31 -0
  40. data/app/workflows/spree/carts/add_item.rb +3 -1
  41. data/app/workflows/spree/carts/complete.rb +3 -1
  42. data/app/workflows/spree/carts/merge.rb +44 -0
  43. data/app/workflows/spree/carts/recalculate.rb +5 -2
  44. data/app/workflows/spree/carts/upsert_items.rb +45 -0
  45. data/app/workflows/spree/gift_cards/apply.rb +12 -0
  46. data/app/workflows/spree/gift_cards/destroy.rb +96 -0
  47. data/app/workflows/spree/gift_cards/remove.rb +4 -4
  48. data/app/workflows/spree/invitations/accept.rb +15 -0
  49. data/app/workflows/spree/payments/handle_webhook.rb +15 -8
  50. data/config/locales/ar.yml +15 -0
  51. data/config/locales/be.yml +15 -0
  52. data/config/locales/bg.yml +15 -0
  53. data/config/locales/ca.yml +15 -0
  54. data/config/locales/cs.yml +15 -0
  55. data/config/locales/da.yml +15 -0
  56. data/config/locales/de-CH.yml +15 -0
  57. data/config/locales/de.yml +15 -0
  58. data/config/locales/el.yml +15 -0
  59. data/config/locales/en.yml +19 -0
  60. data/config/locales/es-CL.yml +15 -0
  61. data/config/locales/es-EC.yml +15 -0
  62. data/config/locales/es-MX.yml +15 -0
  63. data/config/locales/es.yml +15 -0
  64. data/config/locales/et.yml +15 -0
  65. data/config/locales/fa.yml +15 -0
  66. data/config/locales/fi.yml +15 -0
  67. data/config/locales/fr.yml +15 -0
  68. data/config/locales/hu.yml +15 -0
  69. data/config/locales/id.yml +15 -0
  70. data/config/locales/it.yml +15 -0
  71. data/config/locales/ja.yml +15 -0
  72. data/config/locales/km.yml +15 -0
  73. data/config/locales/ko.yml +15 -0
  74. data/config/locales/ku.yml +15 -0
  75. data/config/locales/lt.yml +15 -0
  76. data/config/locales/lv.yml +15 -0
  77. data/config/locales/nb.yml +15 -0
  78. data/config/locales/ne.yml +15 -0
  79. data/config/locales/nl.yml +15 -0
  80. data/config/locales/pl.yml +15 -0
  81. data/config/locales/pt-BR.yml +15 -0
  82. data/config/locales/pt.yml +15 -0
  83. data/config/locales/ro.yml +15 -0
  84. data/config/locales/ru.yml +15 -0
  85. data/config/locales/sk.yml +15 -0
  86. data/config/locales/sl-SI.yml +15 -0
  87. data/config/locales/sv.yml +15 -0
  88. data/config/locales/th.yml +15 -0
  89. data/config/locales/tr.yml +15 -0
  90. data/config/locales/uk.yml +15 -0
  91. data/config/locales/vi.yml +15 -0
  92. data/config/locales/zh-CN.yml +15 -0
  93. data/config/locales/zh-TW.yml +15 -0
  94. data/db/migrate/20261124000001_set_default_fee_total_on_spree_orders.rb +19 -0
  95. data/db/migrate/20261125100001_add_created_by_ip_address_to_spree_api_keys.rb +7 -0
  96. data/lib/spree/core/dependencies.rb +1 -0
  97. data/lib/spree/core/previews/api_key_preview.rb +29 -0
  98. data/lib/spree/core/version.rb +1 -1
  99. data/lib/spree/core.rb +1 -1
  100. data/lib/spree/iso_data.rb +3 -1
  101. data/lib/spree/reporting/query.rb +19 -2
  102. data/lib/spree/testing_support/common_rake.rb +10 -3
  103. data/lib/tasks/cli.rake +4 -2
  104. data/lib/tasks/typed_adjustments_migration.rake +4 -1
  105. metadata +13 -4
@@ -32,6 +32,9 @@ module Spree
32
32
  include Spree::Purchase::QuantityRules
33
33
  include Spree::Purchase::PurchaseOrder
34
34
  include Spree::Purchase::Market
35
+ # The market the order was sold in, kept after that market is deleted:
36
+ # its withdrawal period and return window still apply to the order.
37
+ belongs_to :market, -> { with_deleted }, class_name: 'Spree::Market', inverse_of: :orders
35
38
  include Spree::Purchase::Currency
36
39
  include Spree::Purchase::Locale
37
40
  include Spree::Purchase::DigitalItems
@@ -46,6 +49,7 @@ module Spree
46
49
  include Spree::Purchase::Totals
47
50
  include Spree::Purchase::Lifecycle
48
51
  include Spree::Purchase::DeprecatedAliases
52
+ include Spree::Purchase::Warnings
49
53
  has_spree_number prefix: 'R'
50
54
 
51
55
  include Spree::NumberIdentifier
@@ -74,10 +78,6 @@ module Spree
74
78
  :payment_total, :amount_due, :fee_total,
75
79
  :commission_amount_total, :commission_tax_total, :commission_total
76
80
 
77
-
78
- # Transient warnings populated by remove_out_of_stock_items! and ensure_available_delivery_rates
79
- attribute :warnings, default: -> { [] }
80
-
81
81
  # Removes out-of-stock/discontinued items and populates warnings.
82
82
  # Returns self (reloaded if items were removed) with warnings set.
83
83
  # Captured before the call because removing items reloads the order, which
@@ -27,6 +27,12 @@ module Spree
27
27
 
28
28
  include Spree::PaymentSessionTransitions
29
29
 
30
+ # Statuses after which a session's intent can no longer take money:
31
+ # placement cancels the provider intent, and an expired session's intent
32
+ # is gone. A failed session is not one of them — a declined confirm can
33
+ # leave its intent payable (see +unused+).
34
+ RETIRED_STATUSES = %w[canceled expired].freeze
35
+
30
36
  scope :not_expired, -> { where('expires_at IS NULL OR expires_at > ?', Time.current) }
31
37
  scope :active, -> { not_expired.where(status: %w[pending processing]) }
32
38
  # A declined confirm marks the session failed while its intent can still
@@ -55,6 +61,19 @@ module Spree
55
61
  #
56
62
  # @param metadata [Hash] gateway-specific metadata
57
63
  # @return [Spree::Payment] the payment record
64
+ # The payment settled from this session: its owner's payment under the
65
+ # session's payment method carrying the gateway's identifier, the row
66
+ # find_or_create_payment! creates. The +payment+ association matches the
67
+ # identifier alone, which gateways only keep unique per payment method,
68
+ # so it can return another method's or another owner's payment.
69
+ #
70
+ # @return [Spree::Payment, nil]
71
+ def own_payment
72
+ return unless persisted?
73
+
74
+ owner&.payments&.find_by(payment_method_id: payment_method_id, response_code: external_id)
75
+ end
76
+
58
77
  def find_or_create_payment!(metadata = {})
59
78
  # An unsaved session has no identity to key a payment to, and nothing
60
79
  # has settled against it.
@@ -64,7 +83,8 @@ module Spree
64
83
  # one, so the requirement is skipped on every load, not just at creation
65
84
  # — a later capture webhook transitions the same row and would otherwise
66
85
  # fail source validation.
67
- return skip_source_requirement(payment) if payment.present?
86
+ existing = own_payment
87
+ return skip_source_requirement(existing) if existing
68
88
 
69
89
  # Keyed on the gateway's own identifier alone. Never on the amount: a
70
90
  # session whose amount moved is still the same intent, and a second row
@@ -2,6 +2,8 @@
2
2
 
3
3
  module Spree
4
4
  class PriceHistory < Spree.base_class
5
+ has_prefix_id :pricehist
6
+
5
7
  belongs_to :price, class_name: 'Spree::Price'
6
8
  belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'
7
9
 
@@ -30,9 +30,13 @@ module Spree
30
30
  # Associations
31
31
  #
32
32
  belongs_to :promotion_category, optional: true
33
- has_many :promotion_rules, autosave: true, dependent: :destroy
33
+ # Rules and actions are ordered so they read in creation order:
34
+ # PostgreSQL moves an updated row within unordered results.
35
+ has_many :promotion_rules, -> { order(:id) }, class_name: 'Spree::PromotionRule', autosave: true,
36
+ dependent: :destroy, inverse_of: :promotion
34
37
  alias rules promotion_rules
35
- has_many :promotion_actions, autosave: true, dependent: :destroy
38
+ has_many :promotion_actions, -> { order(:id) }, class_name: 'Spree::PromotionAction', autosave: true,
39
+ dependent: :destroy, inverse_of: :promotion
36
40
  alias actions promotion_actions
37
41
  has_many :coupon_codes, -> { order(created_at: :asc) }, dependent: :destroy, class_name: 'Spree::CouponCode'
38
42
  has_many :order_promotions, class_name: 'Spree::OrderPromotion'
@@ -51,6 +51,34 @@ module Spree
51
51
  nil
52
52
  end
53
53
 
54
+ # The registered engine an API caller names by its shorthand, or nil. Matches
55
+ # the shorthand only, so a Ruby class name arriving over the API is unknown.
56
+ #
57
+ # @param api_type [String] e.g. "internal", "avalara"
58
+ # @return [Class, nil]
59
+ def self.registered(api_type)
60
+ Spree::ApiTyped.find(Spree.tax_providers, api_type)
61
+ end
62
+
63
+ # Tax codes a merchant can search when classifying a tax category, as
64
+ # `[{ code:, description: }]`. Nil for an engine with no catalogue of codes
65
+ # to search, Spree's own included.
66
+ #
67
+ # @param store [Spree::Store]
68
+ # @param query [String]
69
+ # @return [Array<Hash>, nil]
70
+ def self.tax_codes(_store, query:)
71
+ nil
72
+ end
73
+
74
+ # Whether this engine offers {.tax_codes}, which decides whether the admin
75
+ # searches as a merchant types a tax category's code.
76
+ #
77
+ # @return [Boolean]
78
+ def self.tax_code_lookup?
79
+ method(:tax_codes).owner != Spree::TaxProvider::Base.singleton_class
80
+ end
81
+
54
82
  # The declared limits with the strings a merchant can act on. A capability
55
83
  # with no translation degrades to its humanized key rather than a missing
56
84
  # translation, so an extension that declares one without shipping strings
@@ -80,6 +108,7 @@ module Spree
80
108
  available: available_for_store?(store),
81
109
  unsupported_capabilities: unsupported_capability_details,
82
110
  exemption_reason_codes: exemption_reason_codes&.map { |code, label| { value: code.to_s, label: label.to_s } },
111
+ tax_code_lookup: tax_code_lookup?,
83
112
  default: name == Spree.default_tax_provider.to_s
84
113
  }
85
114
  end
@@ -0,0 +1,16 @@
1
+ module Spree
2
+ module Emails
3
+ # Never add the token or its digest: an email must not carry a credential.
4
+ class ApiKeySerializer < BaseSerializer
5
+ attributes :name, :token_prefix, :scopes, :created_by_ip_address
6
+
7
+ attribute :created_at do |api_key|
8
+ api_key.created_at&.iso8601
9
+ end
10
+
11
+ attribute :created_by_name do |api_key|
12
+ api_key.created_by.try(:actor_label)
13
+ end
14
+ end
15
+ end
16
+ end
@@ -27,10 +27,14 @@ module Spree
27
27
  # the transaction, leaving the address rows written above behind.
28
28
  raise ActiveRecord::RecordInvalid, @order unless @order.update(@params)
29
29
 
30
- process_items(items_param) if items_param
31
-
32
30
  # An address row edited in place keeps its id, so an edit to the fields a quote reads counts too.
31
+ # Read before releasing the previous customer's balance: the removal
32
+ # services reload the order, which drops the address's saved changes.
33
33
  destination_changed = @order.ship_address_id != ship_address_id_before || @order.ship_address&.saved_change_to_destination?
34
+
35
+ release_previous_customer_balance if @order.saved_change_to_customer_id? && !@order.completed?
36
+ process_items(items_param) if items_param
37
+
34
38
  build_fulfillments(keep_selection: !destination_changed) if items_param || destination_changed
35
39
 
36
40
  @order.recalculate_totals!
@@ -93,6 +97,32 @@ module Spree
93
97
  propagate_step_failure!(result, fallback: 'Failed to update items on order') if result.failure?
94
98
  end
95
99
 
100
+ # Store credit and a named gift card pay only for their owner's orders,
101
+ # so a draft that changes hands gives back what the previous customer
102
+ # put on it. A gift card without a named owner is spendable by anyone
103
+ # holding its code, so it stays.
104
+ def release_previous_customer_balance
105
+ gift_card = @order.gift_card
106
+
107
+ if gift_card.nil?
108
+ # Nothing to give back: skip the service, which reloads the order.
109
+ return unless @order.payments.store_credits.valid.exists?
110
+
111
+ result = Spree.store_credit_remove_service.call(order: @order)
112
+ propagate_step_failure!(result, fallback: I18n.t('spree.store_credit_paid_by_previous_customer')) if result.failure?
113
+ elsif gift_card.customer_id.present? && gift_card.customer_id != @order.customer_id
114
+ # The remove workflow voids only checkout payments and would detach
115
+ # the card from one already captured, so refuse as store credit does.
116
+ if @order.payments.store_credits.valid.where.not(status: 'checkout').exists?
117
+ @order.errors.add(:base, I18n.t('spree.gift_card_paid_by_previous_customer'))
118
+ raise ActiveRecord::RecordInvalid, @order
119
+ end
120
+
121
+ result = Spree.gift_card_remove_workflow.call(order: @order)
122
+ propagate_step_failure!(result, fallback: 'Failed to remove gift card from order') if result.failure?
123
+ end
124
+ end
125
+
96
126
  def build_fulfillments(keep_selection:)
97
127
  result = Spree::Orders::BuildFulfillments.call(order: @order, keep_selection: keep_selection)
98
128
  propagate_step_failure!(result, fallback: 'Failed to build shipments') if result.failure?
@@ -42,6 +42,11 @@ module Spree
42
42
  #
43
43
  # A container whose own marker happens to fall within the bytes read is
44
44
  # identified outright and never reaches the tie-break at all.
45
+ #
46
+ # The tie-break only ever names an office format. No image is stored in
47
+ # one of these containers, so an image extension never settles it: a zip
48
+ # named `photo.png` is refused, which matters wherever the file is then
49
+ # handed to an image processor that cannot read it.
45
50
  CONTAINER_CONTENT_TYPES = %w[application/zip application/x-ole-storage].freeze
46
51
 
47
52
  # Plain-text formats carry no signature at all, so the bytes can only prove
@@ -78,6 +83,19 @@ module Spree
78
83
  end
79
84
  end
80
85
 
86
+ # Checks a blob that is about to be attached but is not on the record yet —
87
+ # a signed id kept aside until the record saves — against the same
88
+ # allowlist. Its bytes are already in storage, so they are read from there.
89
+ #
90
+ # @param record [ActiveRecord::Base] the record the allowlist resolves against
91
+ # @param blob [ActiveStorage::Blob]
92
+ # @return [Boolean]
93
+ def permitted_blob?(record, blob)
94
+ permitted = permitted_content_types(record)
95
+
96
+ permitted.empty? || permitted_bytes?(blob, nil, permitted)
97
+ end
98
+
81
99
  private
82
100
 
83
101
  def permitted_content_types(record)
@@ -129,7 +147,10 @@ module Spree
129
147
  return permitted_plain_text?(blob, head, permitted) if UNIDENTIFIED_CONTENT_TYPES.include?(detected)
130
148
  return false unless CONTAINER_CONTENT_TYPES.include?(detected)
131
149
 
132
- permitted.include?(type_from_extension(blob))
150
+ extension_type = type_from_extension(blob)
151
+ return false if extension_type.nil? || extension_type.start_with?('image/')
152
+
153
+ permitted.include?(extension_type)
133
154
  end
134
155
 
135
156
  def permitted_plain_text?(blob, head, permitted)
@@ -170,11 +191,16 @@ module Spree
170
191
  nil
171
192
  end
172
193
 
194
+ # A positive-length read of an empty file returns nil rather than an empty
195
+ # string. It is turned back into an empty string here: nil would send the
196
+ # check to storage, which holds nothing yet, and an empty file would then
197
+ # pass as unreadable instead of being refused as no file at all.
198
+ #
173
199
  # @return [String, nil] the head of a file not yet uploaded, leaving the
174
200
  # caller's IO rewound so the upload itself still sees the whole thing
175
201
  def pending_bytes(attachable)
176
202
  case attachable
177
- when Pathname then attachable.open('rb') { |file| file.read(MAGIC_BYTES_LENGTH) }
203
+ when Pathname then attachable.open('rb') { |file| file.read(MAGIC_BYTES_LENGTH) || +'' }
178
204
  when Hash then read_head(attachable[:io])
179
205
  else read_head(attachable)
180
206
  end
@@ -188,7 +214,7 @@ module Spree
188
214
 
189
215
  begin
190
216
  io.rewind
191
- io.read(MAGIC_BYTES_LENGTH)
217
+ io.read(MAGIC_BYTES_LENGTH) || +''
192
218
  ensure
193
219
  io.rewind
194
220
  end
@@ -0,0 +1,31 @@
1
+ ---
2
+ subject: "{{ 'api_key_mailer.secret_key_created.subject' | t: store_name: store.name }}"
3
+ ---
4
+ {% assign created_at = api_key.created_at | date: '%Y-%m-%d %H:%M %Z' %}
5
+ {% assign key_preview = api_key.token_prefix | append: '…' %}
6
+ {% assign scopes = api_key.scopes | join: ', ' %}
7
+ <mj-section>
8
+ <mj-column css-class="hero">
9
+ <mj-text mj-class="heading">{{ 'api_key_mailer.secret_key_created.heading' | t: store_name: store.name }}</mj-text>
10
+ {% if user.first_name != blank %}<mj-text mj-class="greeting">{{ 'api_key_mailer.secret_key_created.greeting' | t: name: user.first_name }}</mj-text>{% endif %}
11
+ {% if api_key.created_by_name != blank %}
12
+ <mj-text mj-class="lead">{{ 'api_key_mailer.secret_key_created.message' | t: creator_name: api_key.created_by_name, key_name: api_key.name, store_name: store.name }}</mj-text>
13
+ {% else %}
14
+ <mj-text mj-class="lead">{{ 'api_key_mailer.secret_key_created.message_without_creator' | t: key_name: api_key.name, store_name: store.name }}</mj-text>
15
+ {% endif %}
16
+ <mj-text mj-class="lead">{{ 'api_key_mailer.secret_key_created.warning' | t }}</mj-text>
17
+ <mj-button href="{{ review_url }}">{{ 'api_key_mailer.secret_key_created.action' | t }}</mj-button>
18
+ </mj-column>
19
+ </mj-section>
20
+ <mj-section padding="48px 0 0">
21
+ <mj-column>
22
+ <mj-table css-class="summary">
23
+ {% render 'spree/shared/summary_row', label: 'api_key_mailer.secret_key_created.name_label', value: api_key.name, translate: true %}
24
+ {% render 'spree/shared/summary_row', label: 'api_key_mailer.secret_key_created.key_label', value: key_preview, translate: true %}
25
+ {% if scopes != blank %}{% render 'spree/shared/summary_row', label: 'api_key_mailer.secret_key_created.scopes_label', value: scopes, translate: true %}{% endif %}
26
+ {% if api_key.created_by_name != blank %}{% render 'spree/shared/summary_row', label: 'api_key_mailer.secret_key_created.created_by_label', value: api_key.created_by_name, translate: true %}{% endif %}
27
+ {% render 'spree/shared/summary_row', label: 'api_key_mailer.secret_key_created.created_at_label', value: created_at, translate: true %}
28
+ {% if api_key.created_by_ip_address != blank %}{% render 'spree/shared/summary_row', label: 'api_key_mailer.secret_key_created.ip_address_label', value: api_key.created_by_ip_address, translate: true %}{% endif %}
29
+ </mj-table>
30
+ </mj-column>
31
+ </mj-section>
@@ -85,7 +85,9 @@ module Spree
85
85
  # caller's in-memory changes (pricing warnings).
86
86
  def guard_completion_claim_in_lock
87
87
  return unless guarded_cart?
88
- return unless completion_holds?(Spree::Cart.lock.find(cart.id))
88
+ # Uncached: the query cache could answer the settlement queries with
89
+ # the unlocked read +guard_completion_claim+ made before the lock.
90
+ return unless Spree::Cart.uncached { completion_holds?(Spree::Cart.lock.find(cart.id)) }
89
91
 
90
92
  reject_claimed_cart
91
93
  end
@@ -124,7 +124,9 @@ module Spree
124
124
  end
125
125
 
126
126
  def guard_concurrent_completion
127
- failure(cart, code: 'completion_in_progress') if cart.completion_claimed?
127
+ # Not completion_claimed?: that also holds a cart whose payment session
128
+ # settled, and completing such a cart is exactly what has to happen.
129
+ failure(cart, code: 'completion_in_progress') if cart.completion_attempt_claimed?
128
130
  end
129
131
 
130
132
  # A batch code this cart no longer holds no longer discounts it, so the
@@ -27,6 +27,7 @@ module Spree
27
27
  super
28
28
 
29
29
  halt!(cart) if other_cart.nil? || other_cart.id == cart.id
30
+ step :ensure_carts_unclaimed
30
31
  step :ensure_matching_currency
31
32
 
32
33
  # Veto point — before anything moves, so a rejection leaves both
@@ -34,6 +35,11 @@ module Spree
34
35
  run_hooks :validate
35
36
 
36
37
  ApplicationRecord.transaction do
38
+ # Both rows stay locked until the merge commits, so a payment
39
+ # session settling on either cart (PaymentSession#settle_payment!
40
+ # runs under the owner's lock) waits for the merge or makes it
41
+ # refuse — it cannot land between the check and the destroy.
42
+ step :lock_unclaimed_carts
37
43
  step :move_line_items
38
44
  # Inside the transaction and before the absorbed lines are deleted,
39
45
  # so an extension can move what it keeps against them.
@@ -50,6 +56,44 @@ module Spree
50
56
 
51
57
  private
52
58
 
59
+ # Neither cart may change while a completion attempt holds it or a
60
+ # gateway has taken money for it: merging would change the totals that
61
+ # money was charged for. The folded-in cart is destroyed, so it must
62
+ # also have no payment session the gateway may still settle — a
63
+ # session can be captured while still +pending+ here, and destroying
64
+ # it leaves the webhook nothing to record the payment against.
65
+ #
66
+ # A fast refusal before the validate hooks run; the answer that counts
67
+ # is +lock_unclaimed_carts+, read under the row locks.
68
+ def ensure_carts_unclaimed
69
+ return unless [cart, other_cart].any?(&:completion_claimed?) || other_cart.payment_session_open?
70
+
71
+ reject_claimed_carts
72
+ end
73
+
74
+ # Locks both carts in id order — the order every merge takes them in,
75
+ # so two merges over the same pair cannot deadlock — and checks them
76
+ # again from the locked rows. Uncached: the query cache could otherwise
77
+ # answer with the unlocked read +ensure_carts_unclaimed+ made.
78
+ def lock_unclaimed_carts
79
+ held = Spree::Cart.uncached do
80
+ locked = Spree::Cart.lock.where(id: [cart.id, other_cart.id]).order(:id).to_a
81
+ # A cart deleted since the merge began is not one to fold either.
82
+ locked.size < 2 || locked.any? { |locked_cart| claimed_or_unsafe_to_drain?(locked_cart) }
83
+ end
84
+
85
+ reject_claimed_carts if held
86
+ end
87
+
88
+ def claimed_or_unsafe_to_drain?(locked_cart)
89
+ locked_cart.completed_at.present? || locked_cart.completion_claimed? ||
90
+ (locked_cart.id == other_cart.id && locked_cart.payment_session_open?)
91
+ end
92
+
93
+ def reject_claimed_carts
94
+ failure(cart, code: 'completion_in_progress', message: I18n.t('spree.cart_completion_in_progress'))
95
+ end
96
+
53
97
  def ensure_matching_currency
54
98
  return if other_cart.currency == cart.currency
55
99
 
@@ -33,9 +33,12 @@ module Spree
33
33
 
34
34
  private
35
35
 
36
+ # A gift card's payment stays, since RecalculateTotals resizes it to the
37
+ # new total; plain store credit is never resized, so it is dropped.
36
38
  def unapply_stale_payment_sources
37
- cart.remove_gift_card if cart.gift_card.present?
38
- cart.payments.store_credits.checkout.destroy_all if cart.payments.store_credits.checkout.any?
39
+ stale = cart.payments.store_credits.checkout
40
+ stale = stale.where.not(source: cart.gift_card.store_credits) if cart.gift_card.present?
41
+ stale.destroy_all
39
42
  end
40
43
 
41
44
  def rebuild_delivery_proposals
@@ -40,6 +40,14 @@ module Spree
40
40
  super
41
41
  @warnings = []
42
42
 
43
+ # A cart a completion attempt holds, or one a gateway has already
44
+ # taken money for, must not change under the purchase it supplies —
45
+ # emptied, it can no longer complete and the buyer stays charged
46
+ # without an order. The Store API fences this under its cart lock;
47
+ # direct callers (the out-of-stock sweep on a cart read, the
48
+ # line-item removal job) have to be refused here.
49
+ step :guard_completion_claim
50
+
43
51
  step :resolve_items
44
52
  return success(cart) if resolved_items.empty?
45
53
 
@@ -50,6 +58,9 @@ module Spree
50
58
  external_step :resolve_prices
51
59
 
52
60
  ApplicationRecord.transaction do
61
+ # Again under the row lock: the external steps above can take a
62
+ # while, and the cart may have been claimed or paid since.
63
+ step :guard_completion_claim_in_lock
53
64
  step :apply_items
54
65
  step :handle_stock_reservations if cart.in_checkout?
55
66
  step :recalculate, with: -> { Spree.cart_recalculate_workflow } if recalculate?
@@ -70,6 +81,40 @@ module Spree
70
81
 
71
82
  attr_reader :resolved_items
72
83
 
84
+ # Draft orders (the admin path, Spree::Orders::UpsertItems) carry no
85
+ # completion claim — only a cart does. Read from a fresh copy of the
86
+ # row: the caller's instance may predate the claim. Mirrors
87
+ # Spree::Carts::AddItem, with the same error code.
88
+ def guard_completion_claim
89
+ return unless guarded_cart?
90
+ return unless completion_holds?(Spree::Cart.find(cart.id))
91
+
92
+ reject_claimed_cart
93
+ end
94
+
95
+ def guard_completion_claim_in_lock
96
+ return unless guarded_cart?
97
+ # Uncached: the query cache could answer the settlement queries with
98
+ # the unlocked read +guard_completion_claim+ made before the lock.
99
+ return unless Spree::Cart.uncached { completion_holds?(Spree::Cart.lock.find(cart.id)) }
100
+
101
+ reject_claimed_cart
102
+ end
103
+
104
+ def guarded_cart?
105
+ cart.is_a?(Spree::Cart) && cart.persisted?
106
+ end
107
+
108
+ # A finished cart answers false to +completion_claimed?+ (finalize
109
+ # clears the claim) and is refused on its own.
110
+ def completion_holds?(fresh_cart)
111
+ fresh_cart.completed_at.present? || fresh_cart.completion_claimed?
112
+ end
113
+
114
+ def reject_claimed_cart
115
+ failure(cart, code: 'completion_in_progress', message: I18n.t('spree.cart_completion_in_progress'))
116
+ end
117
+
73
118
  # The cart side recalculates here because nothing else will. The order
74
119
  # side overrides this: admin edits run items, fulfillments and coupons
75
120
  # as one pipeline and recalculate once at the end of it.
@@ -49,6 +49,9 @@ module Spree
49
49
  # card-then-record, which is the order Spree::GiftCards::Remove
50
50
  # uses and which the transaction would otherwise keep.
51
51
  step :lock_affected_records
52
+ # Again under the lock: the order may have been placed since the
53
+ # caller loaded it.
54
+ step :ensure_order_open
52
55
  step :release_open_holds
53
56
  run_hooks :release_holds
54
57
 
@@ -69,6 +72,8 @@ module Spree
69
72
  private
70
73
 
71
74
  def ensure_applicable
75
+ ensure_order_open
76
+
72
77
  # A gift card and a store credit are two ways of paying from a
73
78
  # balance; mixing them on one order is not supported.
74
79
  failure(order, :gift_card_using_store_credit_error) if order.using_store_credit?
@@ -88,6 +93,13 @@ module Spree
88
93
  failure(order, :gift_card_mismatched_customer) if gift_card.customer != order.customer
89
94
  end
90
95
 
96
+ # A placed order never takes the payment this creates, and
97
+ # Spree::GiftCards::Remove refuses it, so a card drawn down here could
98
+ # never be given back.
99
+ def ensure_order_open
100
+ failure(order, :apply_gift_card_on_completed_order_error) if order.completed?
101
+ end
102
+
91
103
  def lock_gift_card
92
104
  gift_card.lock!
93
105
  end
@@ -0,0 +1,96 @@
1
+ module Spree
2
+ module GiftCards
3
+ # Deletes a gift card. A card applied to an open cart or draft order is
4
+ # taken off it first through Spree.gift_card_remove_workflow, which voids
5
+ # the store credit payment made from the card and restores the amount
6
+ # due. Deleting the card while leaving that payment would let the order
7
+ # be placed paid by a card that no longer exists, and refusing instead
8
+ # would leave a card on an abandoned guest cart undeletable, because
9
+ # holds never expire on their own.
10
+ #
11
+ # Refused while a checkout is completing with the card (its totals are
12
+ # fixed and money may be at the gateway), and for a card the model will
13
+ # not delete (redeemed or partially redeemed). A refusal rolls back any
14
+ # hold already released, so nothing changes.
15
+ class Destroy < Spree::Workflow
16
+ hooks :validate, :after_destroy
17
+
18
+ # Carts and draft orders the card was taken off.
19
+ # @return [Array<Spree::Cart, Spree::Order>]
20
+ attr_reader :released_holds
21
+
22
+ # @param gift_card [Spree::GiftCard]
23
+ # @return [Spree::ServiceModule::Result] value is the destroyed gift card
24
+ def perform(gift_card:)
25
+ super
26
+
27
+ run_hooks :validate
28
+
29
+ # Holds are locked before the card, the order Spree::GiftCards::Apply
30
+ # and Remove use, so this cannot deadlock against either. The card
31
+ # stays locked from the check to the delete, so a checkout cannot
32
+ # apply it in between.
33
+ ApplicationRecord.transaction do
34
+ step :lock_holds
35
+ step :release_open_holds
36
+ step :lock_gift_card
37
+ step :ensure_not_being_completed
38
+ step :destroy_gift_card
39
+ run_hooks :after_destroy
40
+ end
41
+
42
+ success(gift_card)
43
+ end
44
+
45
+ private
46
+
47
+ def lock_holds
48
+ @holds = gift_card.open_holds
49
+
50
+ @holds.group_by(&:class).each do |klass, records|
51
+ klass.where(id: records.map(&:id)).order(:id).lock.to_a
52
+ end
53
+ end
54
+
55
+ # Re-reads each hold under its lock: the list was gathered before it,
56
+ # so the hold may have moved on to another card, completed or claimed
57
+ # completion since. Those are skipped, and a claimed one then fails
58
+ # +ensure_not_being_completed+.
59
+ def release_open_holds
60
+ @released_holds = []
61
+
62
+ @holds.each do |hold|
63
+ hold.reload
64
+ next unless hold.gift_card_id == gift_card.id
65
+ next if hold.completed? || claimed_for_completion?(hold)
66
+
67
+ result = Spree.gift_card_remove_workflow.call(order: hold)
68
+ failure(gift_card, :gift_card_held_by_another_order) if result.failure?
69
+
70
+ @released_holds << hold
71
+ end
72
+ end
73
+
74
+ def lock_gift_card
75
+ gift_card.lock!
76
+ end
77
+
78
+ def ensure_not_being_completed
79
+ failure(gift_card, :gift_card_held_by_another_order) if gift_card.holds_being_completed.any?
80
+ end
81
+
82
+ # The model's before_destroy guard has the final say (a redeemed card,
83
+ # or any hold left) and adds the reason to the card's errors.
84
+ def destroy_gift_card
85
+ failure(gift_card) unless gift_card.destroy
86
+ end
87
+
88
+ # Mirrors Spree::GiftCard#holds_being_completed.
89
+ def claimed_for_completion?(hold)
90
+ return hold.completion_claimed? if hold.is_a?(Spree::Cart)
91
+
92
+ hold.cart&.reload&.completion_claimed? || false
93
+ end
94
+ end
95
+ end
96
+ end
@@ -16,10 +16,10 @@ module Spree
16
16
  run_hooks :validate
17
17
 
18
18
  order.with_lock do
19
- # Re-checked inside the lock: the nil check above runs before it, so
20
- # a concurrent remove can detach the card in between and leave every
21
- # step below dereferencing nil.
22
- @gift_card = order.reload.gift_card
19
+ # Re-checked inside the lock, whose reload gives a fresh read: the nil
20
+ # check above runs before it, so a concurrent remove can detach the
21
+ # card in between and leave every step below dereferencing nil.
22
+ @gift_card = order.gift_card
23
23
  next if @gift_card.nil?
24
24
 
25
25
  step :void_payments
@@ -19,6 +19,7 @@ module Spree
19
19
  run_hooks :validate
20
20
 
21
21
  ApplicationRecord.transaction do
22
+ step :lock_invitation
22
23
  step :grant_role
23
24
  step :mark_accepted
24
25
  run_hooks :after_accept
@@ -36,6 +37,20 @@ module Spree
36
37
  failure(invitation, :invitation_invitee_missing) if invitation.invitee.blank?
37
38
  end
38
39
 
40
+ # Re-read under a row lock: a removal from staff revokes the invitation
41
+ # in its own transaction, and an acceptance racing it must not grant the
42
+ # role back once that has committed.
43
+ def lock_invitation
44
+ current = Spree::Invitation.lock.find_by(id: invitation.id)
45
+ failure(invitation, :invitation_not_acceptable) unless still_acceptable?(current)
46
+ end
47
+
48
+ # A resend that committed after the caller loaded the invitation rotated
49
+ # its token, so the link the caller presented no longer works.
50
+ def still_acceptable?(current)
51
+ current.present? && !current.accepted? && current.token == invitation.token
52
+ end
53
+
39
54
  def grant_role
40
55
  invitation.role_user = invitation.resource.add_user(invitation.invitee, invitation.role)
41
56
  end