Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Move a gift card to the cart that presents its code (#14577)

Damian Legawiecd5ce7fc33735
diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts/gift_card_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/gift_card_controller_spec.rb
index 7a05da1e40..00b1588a3d 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/carts/gift_card_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/gift_card_controller_spec.rb
@@ -53,6 +53,43 @@ RSpec.describe Spree::Api::V3::Store::Carts::GiftCardsController, type: :control
expect(response).to have_http_status(:unprocessable_content)
end
+ context 'when the card is already held by the customer\'s other cart' do
+ let!(:other_cart) { create(:cart_with_line_items, store: store, customer: user) }
+
+ before do
+ other_cart.update_column(:total, 50)
+ expect(Spree.gift_card_apply_workflow.call(gift_card: gift_card, order: other_cart)).to be_success
+ end
+
+ it 'moves the card onto this cart' do
+ post :create, params: { cart_id: order.prefixed_id, code: 'giftcard123' }
+
+ expect(response).to have_http_status(:created)
+ expect(order.reload.gift_card).to eq(gift_card)
+ expect(other_cart.reload.gift_card).to be_nil
+ end
+ end
+
+ context 'when the other cart is being completed' do
+ let!(:other_cart) { create(:cart_with_line_items, store: store, customer: user) }
+
+ before do
+ other_cart.update_column(:total, 50)
+ expect(Spree.gift_card_apply_workflow.call(gift_card: gift_card, order: other_cart)).to be_success
+ other_cart.update_column(:completing_at, Time.current)
+ end
+
+ it 'refuses and tells the customer to retry' do
+ post :create, params: { cart_id: order.prefixed_id, code: 'giftcard123' }
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']).to be_present
+
+ expect(order.reload.gift_card).to be_nil
+ expect(other_cart.reload.gift_card).to eq(gift_card)
+ end
+ end
+
context 'with guest spree token' do
let(:guest_order) { create(:cart_with_line_items, store: store, customer: nil) }
diff --git a/spree/core/app/models/spree/gift_card.rb b/spree/core/app/models/spree/gift_card.rb
index 3e51f8d97c..3b8e1afb38 100644
--- a/spree/core/app/models/spree/gift_card.rb
+++ b/spree/core/app/models/spree/gift_card.rb
@@ -39,6 +39,7 @@ module Spree
has_many :store_credits, class_name: 'Spree::StoreCredit', as: :originator
has_many :orders, inverse_of: :gift_card, class_name: 'Spree::Order'
+ has_many :carts, inverse_of: :gift_card, class_name: 'Spree::Cart'
has_many :users, through: :orders, source: :customer
#
@@ -93,6 +94,34 @@ module Spree
%w[code amount expires_at]
end
+ # Carts and draft orders currently holding part of this card's balance.
+ # Applying a card draws it down before anything is paid for, so a card
+ # left on an abandoned cart keeps money locked up until that record is
+ # completed or the card is taken off it. Spree::GiftCards::Apply releases
+ # these holds so the customer presenting the code can spend it again.
+ #
+ # A hold in the middle of a completion attempt is never returned — see
+ # +holds_being_completed+. The two readers partition the same set, so a
+ # hold this one omits for that reason always appears in the other.
+ #
+ # @param except [Spree::Cart, Spree::Order, nil] the record being applied
+ # to, which is not a stale hold
+ # @return [Array<Spree::Cart, Spree::Order>]
+ def open_holds(except: nil)
+ all_holds(except: except).reject { |hold| claimed_by_completion?(hold) }
+ end
+
+ # Holds this card cannot be taken from because a completion attempt holds
+ # them — the balance frees up on its own once the claim resolves or goes
+ # stale, so a caller refused for this reason can tell the customer to
+ # retry rather than that the card is spent.
+ #
+ # @param except [Spree::Cart, Spree::Order, nil]
+ # @return [Array<Spree::Cart, Spree::Order>]
+ def holds_being_completed(except: nil)
+ all_holds(except: except).select { |hold| claimed_by_completion?(hold) }
+ end
+
# Checks if the gift card is editable
# @return [Boolean]
def editable?
@@ -174,6 +203,31 @@ module Spree
private
+ # Ordered by id so concurrent applies lock holds in the same sequence and
+ # cannot form a deadlock cycle between two carts.
+ def all_holds(except: nil)
+ holds = carts.incomplete.order(:id).to_a +
+ orders.incomplete.where.not(status: 'canceled').includes(:cart).order(:id).to_a
+
+ holds.reject { |hold| same_record?(hold, except) }
+ end
+
+ def same_record?(hold, other)
+ other.present? && hold.class == other.class && hold.id == other.id
+ end
+
+ # A record at the gateway has fixed totals and money in flight; taking its
+ # gift card away mid-charge would place an order that no longer adds up.
+ # Checkout stamps the claim on the cart and then copies the card onto a
+ # draft order, so the draft is protected through its originating cart —
+ # that copy is the window where real money is moving.
+ def claimed_by_completion?(hold)
+ case hold
+ when Spree::Cart then hold.completion_claimed?
+ else hold.cart&.completion_claimed? || false
+ end
+ end
+
# Mirrors the machine's bang events: an illegal move raised, so a rejected
# workflow raises here too rather than returning quietly.
def run_gift_card_workflow(workflow)
diff --git a/spree/core/app/workflows/spree/gift_cards/apply.rb b/spree/core/app/workflows/spree/gift_cards/apply.rb
index 1cc837d35c..6c5dc02244 100644
--- a/spree/core/app/workflows/spree/gift_cards/apply.rb
+++ b/spree/core/app/workflows/spree/gift_cards/apply.rb
@@ -10,8 +10,20 @@ module Spree
# kind a store overrides — who may spend a card, on what, and up to how
# much — and because it writes several records that must stand or fall
# together.
+ #
+ # A card already sitting on another open cart is released rather than
+ # refused. That hold is not a payment — nobody has been charged — so
+ # whoever presents the code now takes it, and whoever completes an order
+ # first keeps it. Refusing instead would strand the balance whenever the
+ # other cart is unreachable (another device, a guest session), because
+ # holds never expire on their own. Override the +release_holds+ hook to
+ # refuse instead.
class Apply < Spree::Workflow
- hooks :validate, :after_apply
+ hooks :validate, :release_holds, :after_apply
+
+ # Carts and draft orders whose hold on the card this apply released.
+ # @return [Array<Spree::Cart, Spree::Order>]
+ attr_reader :released_holds
attr_reader :store_credit, :payment
@@ -24,14 +36,31 @@ module Spree
step :ensure_applicable
run_hooks :validate
- order.with_lock do
- step :lock_gift_card
- step :ensure_amount_available
- step :issue_store_credit
- step :draw_down_gift_card
- step :create_payment
- step :recalculate_order
- run_hooks :after_apply
+ # One transaction so a refused release rolls back the ones that
+ # already succeeded. Holds are released BEFORE the card is locked:
+ # Spree::GiftCards::Remove locks its record and then the card, so
+ # taking the card first here would invert that order and deadlock
+ # against any concurrent remove of the same card.
+ ApplicationRecord.transaction do
+ # Every record this workflow touches — the target and each hold —
+ # is locked in one id-ordered pass before anything takes the
+ # gift-card lock. One global order, so two applies whose targets
+ # are each other's holds queue instead of crossing; and never
+ # card-then-record, which is the order Spree::GiftCards::Remove
+ # uses and which the transaction would otherwise keep.
+ step :lock_affected_records
+ step :release_open_holds
+ run_hooks :release_holds
+
+ order.with_lock do
+ step :lock_gift_card
+ step :ensure_amount_available
+ step :issue_store_credit
+ step :draw_down_gift_card
+ step :create_payment
+ step :recalculate_order
+ run_hooks :after_apply
+ end
end
success(order.reload)
@@ -63,12 +92,98 @@ module Spree
gift_card.lock!
end
+ # Locks the target together with every hold, ordered by id within each
+ # class so concurrent applies acquire them in the same sequence.
+ def lock_affected_records
+ @holds_to_release = gift_card.open_holds(except: order)
+
+ (@holds_to_release + [order]).group_by(&:class).each do |klass, records|
+ klass.where(id: records.map(&:id)).order(:id).lock.to_a
+ end
+
+ order.reload
+ end
+
+ # Runs before the balance is read, so the released amount is available
+ # to this order. Releasing is all or nothing with the apply itself: a
+ # refused release fails the whole workflow, which rolls back the ones
+ # that did succeed. Emptying one shopper's cart and then not spending
+ # the balance would be the worst of both outcomes.
+ def release_open_holds
+ @released_holds = []
+ return if @holds_to_release.blank?
+
+ @holds_to_release.each { |hold| release_hold(hold) }
+
+ gift_card.reload
+ end
+
+ # Re-reads the hold under its own lock before removing anything. The
+ # list was gathered outside that lock, so by now the other shopper may
+ # have taken this card off, swapped a different one on, or started a
+ # checkout — and Remove detaches whatever card the record carries at the
+ # time, not the one we meant. A hold that has moved on is skipped, which
+ # includes one that claimed completion in the window: its totals are
+ # fixed and money may already be at the gateway.
+ def release_hold(hold)
+ hold.with_lock do
+ hold.reload
+ next unless hold.gift_card_id == gift_card.id
+ next if hold.completed?
+ next if claimed_since_snapshot?(hold)
+
+ result = Spree.gift_card_remove_workflow.call(order: hold)
+
+ if result.success?
+ @released_holds << hold
+ else
+ report_unreleased_hold(hold, result)
+ failure(order, :gift_card_held_by_another_order)
+ end
+ end
+ end
+
+ # Mirrors Spree::GiftCard#open_holds, which excludes a claimed cart and
+ # a draft order whose originating cart is claimed.
+ def claimed_since_snapshot?(hold)
+ return hold.completion_claimed? if hold.is_a?(Spree::Cart)
+
+ hold.cart&.reload&.completion_claimed? || false
+ end
+
+ def report_unreleased_hold(hold, result)
+ Rails.error.report(
+ Spree::Core::GiftCardHoldReleaseFailed.new(
+ "Gift card #{gift_card.id} could not be released from #{hold.class.name} #{hold.id}: #{result.error}"
+ ),
+ handled: true,
+ context: { order_id: order.id, gift_card_id: gift_card.id, hold_id: hold.id, hold_type: hold.class.name },
+ source: 'spree.core'
+ )
+ end
+
def ensure_amount_available
+ # Releasing a hold changed amount_remaining, so drop anything computed
+ # before that — a stale positive would let a zero balance reach
+ # issue_store_credit and raise there instead of failing here.
+ @amount = nil
return if amount.positive? || order.total.zero?
+ # Distinguish a spent card from one whose balance is briefly locked
+ # up elsewhere — the customer can retry the second, not the first.
+ failure(order, :gift_card_held_by_another_order) if held_elsewhere?
failure(order, :gift_card_no_amount_remaining)
end
+ # Read fresh rather than from the snapshot the release worked from. A
+ # hold created since then was never offered for release, so reporting
+ # the card as spent would be wrong — the balance is recoverable and the
+ # customer should be told to retry.
+ def held_elsewhere?
+ gift_card.holds_being_completed(except: order).any? ||
+ gift_card.open_holds(except: order).any?
+ end
+
def amount
@amount ||= [gift_card.amount_remaining, order.total].min
end
diff --git a/spree/core/app/workflows/spree/gift_cards/remove.rb b/spree/core/app/workflows/spree/gift_cards/remove.rb
index c718f2381b..3be0f8b3eb 100644
--- a/spree/core/app/workflows/spree/gift_cards/remove.rb
+++ b/spree/core/app/workflows/spree/gift_cards/remove.rb
@@ -16,6 +16,12 @@ module Spree
run_hooks :validate
order.with_lock do
+ # Re-checked inside the lock: the nil check above runs before it, so
+ # a concurrent remove can detach the card in between and leave every
+ # step below dereferencing nil.
+ @gift_card = order.reload.gift_card
+ next if @gift_card.nil?
+
step :void_payments
step :restore_gift_card_balance
step :discard_store_credits
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 992e807492..14d1841fe9 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -1115,6 +1115,7 @@ en:
gift_card_canceled: The Gift Card has been canceled.
gift_card_customer_not_logged_in: Gift Card cannot be applied with guest user.
gift_card_expired: The Gift Card has expired.
+ gift_card_held_by_another_order: The Gift Card is being used by another order that is still being placed. Please try again in a few minutes.
gift_card_mismatched_currency: Gift Card cannot be applied with current currency.
gift_card_mismatched_customer: This gift card is associated with another user.
gift_card_no_amount_remaining: The Gift Card has no amount remaining.
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index 8f704ceac0..99f09ceb46 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -817,6 +817,11 @@ module Spree
module Core
class GatewayError < RuntimeError; end
+ # A gift card that could not be taken back off a cart or draft order
+ # holding its balance. No gateway is involved — reported separately so a
+ # money discrepancy is not triaged alongside payment outages.
+ class GiftCardHoldReleaseFailed < RuntimeError; end
+
# A label purchase that failed inside the one-click fulfill path, where
# the parcel ships regardless — reported so the merchant's error tracker
# sees why there is no label.
diff --git a/spree/core/spec/models/spree/gift_card_spec.rb b/spree/core/spec/models/spree/gift_card_spec.rb
index fe581c4d9a..0f0af4945d 100644
--- a/spree/core/spec/models/spree/gift_card_spec.rb
+++ b/spree/core/spec/models/spree/gift_card_spec.rb
@@ -127,6 +127,53 @@ RSpec.describe Spree::GiftCard, type: :model do
end
end
+ describe '#open_holds' do
+ let(:store) { Spree::Store.default }
+ let(:gift_card) { create(:gift_card, store: store) }
+
+ let!(:open_cart) { create(:cart, store: store, gift_card: gift_card) }
+ let!(:open_order) { create(:order, store: store, gift_card: gift_card) }
+ let!(:completed_order) { create(:order, store: store, gift_card: gift_card, completed_at: Time.current) }
+ let!(:canceled_order) { create(:order, store: store, gift_card: gift_card, status: 'canceled') }
+ let!(:unrelated_cart) { create(:cart, store: store) }
+
+ it 'returns only the carts and orders still holding the balance' do
+ expect(gift_card.open_holds).to contain_exactly(open_cart, open_order)
+ end
+
+ it 'excludes the record being applied to' do
+ expect(gift_card.open_holds(except: open_cart)).to contain_exactly(open_order)
+ end
+
+ it 'excludes on type as well as id' do
+ # An Order stand-in carrying the cart's id must not exclude the cart,
+ # and must still exclude the order it really names.
+ stand_in = Spree::Order.new(id: open_cart.id)
+
+ expect(gift_card.open_holds(except: stand_in)).to include(open_cart)
+ expect(gift_card.open_holds(except: Spree::Order.new(id: open_order.id))).not_to include(open_order)
+ end
+
+ context 'when a cart is mid-completion' do
+ before { open_cart.update_column(:completing_at, Time.current) }
+
+ it 'is not releasable' do
+ expect(gift_card.open_holds).to contain_exactly(open_order)
+ end
+
+ it 'is reported as being completed' do
+ expect(gift_card.holds_being_completed).to contain_exactly(open_cart)
+ end
+
+ it 'is not reported once the claim goes stale' do
+ open_cart.update_column(:completing_at, 1.day.ago)
+
+ expect(gift_card.holds_being_completed).to be_empty
+ expect(gift_card.open_holds).to include(open_cart)
+ end
+ end
+ end
+
describe '#display_status' do
context 'when expired' do
let(:gift_card) { build(:gift_card, expires_at: 1.day.ago, status: :active) }
diff --git a/spree/core/spec/models/spree/promotion_handler/coupon_with_gift_card_spec.rb b/spree/core/spec/models/spree/promotion_handler/coupon_with_gift_card_spec.rb
index 98773888cc..51b4a3d37a 100644
--- a/spree/core/spec/models/spree/promotion_handler/coupon_with_gift_card_spec.rb
+++ b/spree/core/spec/models/spree/promotion_handler/coupon_with_gift_card_spec.rb
@@ -22,14 +22,14 @@ describe Spree::PromotionHandler::Coupon, type: :model do
end
end
- context 'when the gift card is applied to another order' do
+ context 'when the gift card is held by another open order' do
let(:old_order) { create(:order, store: store) }
before do
old_order.update_column(:total, 30)
end
- it "doesn't apply the gift card to a new order" do
+ it 'moves the gift card to the order that presents the code' do
old_order.coupon_code = gift_card.code
described_class.new(old_order).apply
@@ -39,8 +39,11 @@ describe Spree::PromotionHandler::Coupon, type: :model do
order.coupon_code = gift_card.code
described_class.new(order).apply
- expect(order.reload.gift_card).to eq(nil)
- expect(order.total_applied_store_credit).to eq(0)
+ expect(order.reload.gift_card).to eq(gift_card)
+ expect(order.total_applied_store_credit).to eq(10)
+
+ expect(old_order.reload.gift_card).to be_nil
+ expect(old_order.total_applied_store_credit).to eq(0)
end
end
diff --git a/spree/core/spec/workflows/spree/gift_cards/apply_spec.rb b/spree/core/spec/workflows/spree/gift_cards/apply_spec.rb
index 8e9f4f3ccb..312a4510a6 100644
--- a/spree/core/spec/workflows/spree/gift_cards/apply_spec.rb
+++ b/spree/core/spec/workflows/spree/gift_cards/apply_spec.rb
@@ -172,6 +172,278 @@ RSpec.describe Spree::GiftCards::Apply do
end
end
+ context 'when the gift card is already held by another open cart' do
+ let(:other_cart) { create(:cart, store: store, customer: order_user) }
+
+ before do
+ other_cart.update_column(:total, 50)
+ expect(Spree.gift_card_apply_workflow.call(gift_card: gift_card, order: other_cart)).to be_success
+ end
+
+ it 'releases the other hold and applies the freed balance here' do
+ expect(gift_card.reload.amount_remaining).to eq(0)
+
+ expect(subject).to be_success
+
+ expect(other_cart.reload.gift_card).to be_nil
+ expect(other_cart.payments.store_credits.checkout).to be_empty
+
+ expect(order.reload.gift_card).to eq(gift_card)
+ expect(order.gift_card_total).to eq(30)
+ expect(gift_card.reload.amount_remaining).to eq(20)
+ end
+
+ it 'reports the released holds' do
+ workflow = described_class.new
+ expect(workflow.call(gift_card: gift_card, order: order)).to be_success
+ expect(workflow.released_holds.map(&:id)).to eq([other_cart.id])
+ end
+
+ context 'when the other hold cannot be released' do
+ before do
+ allow(Spree).to receive(:gift_card_remove_workflow).and_return(failing_remove_workflow)
+ end
+
+ let(:failing_remove_workflow) do
+ double(call: Spree::ServiceModule::Result.new(false, nil, Spree::ServiceModule::ResultError.new('nope')))
+ end
+
+ it 'reports the discrepancy and refuses the apply' do
+ expect(Rails.error).to receive(:report).with(
+ an_instance_of(Spree::Core::GiftCardHoldReleaseFailed),
+ hash_including(handled: true)
+ )
+
+ expect(subject).to be_failure
+ expect(subject.error.value).to eq(:gift_card_held_by_another_order)
+
+ expect(other_cart.reload.gift_card).to eq(gift_card)
+ expect(order.reload.gift_card).to be_nil
+ end
+ end
+ end
+
+ context 'when a hold no longer carries this card' do
+ let!(:other_cart) { create(:cart, store: store, customer: order_user) }
+ let!(:replacement_card) { create(:gift_card, amount: 50, store: store) }
+
+ before do
+ other_cart.update_column(:total, 50)
+ expect(Spree.gift_card_apply_workflow.call(gift_card: gift_card, order: other_cart)).to be_success
+ end
+
+ # The hold list is gathered before each hold is locked. Spree::GiftCards::
+ # Remove detaches whatever card the record carries at the time, so without
+ # a re-check a card swapped in by the other shopper would be stripped and
+ # the wrong balance restored.
+ it 'skips a hold whose card changed after the list was gathered' do
+ workflow = described_class.new
+ workflow.send(:instance_variable_set, :@gift_card, gift_card)
+ workflow.send(:instance_variable_set, :@order, order)
+ workflow.send(:instance_variable_set, :@released_holds, [])
+
+ Spree::Cart.where(id: other_cart.id).update_all(gift_card_id: replacement_card.id)
+
+ expect(Spree.gift_card_remove_workflow).not_to receive(:call)
+ workflow.send(:release_hold, other_cart)
+
+ expect(other_cart.reload.gift_card_id).to eq(replacement_card.id)
+ expect(replacement_card.reload.amount_used).to eq(0)
+ end
+ end
+
+ context 'when several carts hold the card' do
+ let!(:first_hold) { create(:cart, store: store, customer: order_user) }
+ let!(:second_hold) { create(:cart, store: store, customer: order_user) }
+
+ # Applying twice would move the card rather than leave both holding it,
+ # so the second hold is attached directly — the state this workflow has
+ # to cope with when older data or an extension left two rows behind.
+ before do
+ [first_hold, second_hold].each { |hold| hold.update_column(:total, 10) }
+ expect(Spree.gift_card_apply_workflow.call(gift_card: gift_card, order: first_hold)).to be_success
+ second_hold.update_column(:gift_card_id, gift_card.id)
+ end
+
+ it 'releases every hold and reclaims the balance' do
+ expect(subject).to be_success
+
+ expect(first_hold.reload.gift_card).to be_nil
+ expect(second_hold.reload.gift_card).to be_nil
+ expect(order.reload.gift_card).to eq(gift_card)
+ expect(order.gift_card_total).to eq(30)
+ end
+
+ # Every hold row is locked before the first removal takes the card lock,
+ # which the transaction then holds. Locking a hold after that would invert
+ # the record-then-card order Remove uses.
+ it 'locks every affected record before the first removal' do
+ events = []
+
+ allow_any_instance_of(Spree::Cart).to receive(:lock!).and_wrap_original do |original, *args|
+ events << :locked
+ original.call(*args)
+ end
+ allow(Spree.gift_card_remove_workflow).to receive(:call).and_wrap_original do |original, **kwargs|
+ events << :released
+ original.call(**kwargs)
+ end
+
+ expect(subject).to be_success
+
+ # Both holds and the target are locked in the ordered pass before the
+ # first release runs; Remove then re-locks its own record.
+ expect(events.index(:released)).to be > 0
+ expect(events.count(:released)).to eq(2)
+ end
+ end
+
+ context 'when a hold claims completion after the list is gathered' do
+ let!(:other_cart) { create(:cart, store: store, customer: order_user) }
+
+ before do
+ other_cart.update_column(:total, 50)
+ expect(Spree.gift_card_apply_workflow.call(gift_card: gift_card, order: other_cart)).to be_success
+ end
+
+ # open_holds reads before the locks are taken, so a checkout that claims
+ # in that window must still keep its card: its totals are fixed and money
+ # may already be at the gateway.
+ it 'leaves it alone' do
+ allow_any_instance_of(Spree::GiftCard).to receive(:open_holds).and_wrap_original do |original, **kwargs|
+ holds = original.call(**kwargs)
+ Spree::Cart.where(id: other_cart.id).update_all(completing_at: Time.current)
+ holds
+ end
+
+ subject
+
+ expect(other_cart.reload.gift_card).to eq(gift_card)
+ expect(other_cart.payments.checkout.store_credits).to be_present
+ end
+ end
+
+ context 'lock ordering' do
+ let(:other_cart) { create(:cart, store: store, customer: order_user) }
+
+ before do
+ other_cart.update_column(:total, 50)
+ expect(Spree.gift_card_apply_workflow.call(gift_card: gift_card, order: other_cart)).to be_success
+ end
+
+ # Releasing a hold takes the gift-card lock and the transaction keeps it,
+ # so the target must be locked before any release rather than after.
+ it 'locks the target in the same pass as the holds' do
+ locked_ids = []
+
+ allow(Spree::Order).to receive(:where).and_wrap_original do |original, *args|
+ relation = original.call(*args)
+ locked_ids << args.first[:id] if args.first.is_a?(Hash) && args.first.key?(:id)
+ relation
+ end
+
+ expect(subject).to be_success
+
+ # The ordered lock pass covers the target, not just the holds.
+ expect(locked_ids.flatten).to include(order.id)
+ end
+
+ # Spree::GiftCards::Remove locks its record and then the card. Holding the
+ # card while reaching for another record would invert that and deadlock
+ # against a concurrent remove of the same card.
+ it 'releases holds before locking the gift card' do
+ locked = []
+
+ allow_any_instance_of(Spree::GiftCard).to receive(:lock!) do |card|
+ locked << :gift_card
+ card
+ end
+ allow(Spree.gift_card_remove_workflow).to receive(:call).and_wrap_original do |original, **kwargs|
+ locked << :hold_released
+ original.call(**kwargs)
+ end
+
+ expect(subject).to be_success
+ expect(locked.first).to eq(:hold_released)
+ end
+ end
+
+ context 'when the other cart is mid-completion' do
+ let(:other_cart) { create(:cart, store: store, customer: order_user) }
+
+ before do
+ other_cart.update_column(:total, 50)
+ expect(Spree.gift_card_apply_workflow.call(gift_card: gift_card, order: other_cart)).to be_success
+ other_cart.update_column(:completing_at, Time.current)
+ end
+
+ it 'leaves the claimed hold alone and says the card is in use' do
+ expect(subject).to be_failure
+ expect(subject.error.value).to eq(:gift_card_held_by_another_order)
+
+ expect(other_cart.reload.gift_card).to eq(gift_card)
+ expect(order.reload.gift_card).to be_nil
+ end
+
+ context 'when the completion claim has gone stale' do
+ before { other_cart.update_column(:completing_at, 1.day.ago) }
+
+ it 'releases the abandoned hold' do
+ expect(subject).to be_success
+
+ expect(other_cart.reload.gift_card).to be_nil
+ expect(order.reload.gift_card).to eq(gift_card)
+ end
+ end
+ end
+
+ context 'when a draft order from an in-flight checkout holds the card' do
+ let(:completing_cart) { create(:cart, store: store, customer: order_user) }
+ let!(:draft_order) do
+ create(:order, store: store, customer: order_user, cart: completing_cart, status: 'draft').tap do |draft|
+ draft.update_column(:total, 50)
+ expect(Spree.gift_card_apply_workflow.call(gift_card: gift_card, order: draft)).to be_success
+ end
+ end
+
+ before { completing_cart.update_column(:completing_at, Time.current) }
+
+ it 'leaves the draft alone while its cart is being completed' do
+ expect(subject).to be_failure
+ expect(subject.error.value).to eq(:gift_card_held_by_another_order)
+
+ expect(draft_order.reload.gift_card).to eq(gift_card)
+ expect(draft_order.payments.checkout.store_credits).to be_present
+ expect(order.reload.gift_card).to be_nil
+ end
+
+ it 'releases the draft once the completion claim goes stale' do
+ completing_cart.update_column(:completing_at, 1.day.ago)
+
+ expect(subject).to be_success
+
+ expect(draft_order.reload.gift_card).to be_nil
+ expect(order.reload.gift_card).to eq(gift_card)
+ end
+ end
+
+ context 'when the gift card is held by a completed order' do
+ let!(:completed_order) do
+ create(:order, store: store, customer: order_user).tap do |other|
+ other.update_column(:total, 50)
+ expect(Spree.gift_card_apply_workflow.call(gift_card: gift_card, order: other)).to be_success
+ other.update_column(:completed_at, Time.current)
+ end
+ end
+
+ it 'leaves the settled hold alone' do
+ expect(subject).to be_failure
+ expect(subject.error.value).to eq(:gift_card_no_amount_remaining)
+
+ expect(completed_order.reload.gift_card).to eq(gift_card)
+ end
+ end
+
context 'when the order belongs to a non-default store' do
let(:other_store) { create(:store, default: false) }
let(:order) { create(:order, store: other_store, customer: order_user) }