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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: a single-use coupon code is no longer used up by a cart that is never ordered
Damian Legawiec7335a712f1fd
diff --git a/docs/developer/core-concepts/promotions.mdx b/docs/developer/core-concepts/promotions.mdxindex 4e308536f0..5cc4639db7 100644--- a/docs/developer/core-concepts/promotions.mdx+++ b/docs/developer/core-concepts/promotions.mdx@@ -211,7 +211,7 @@ Deleting a promotion doesn't disturb the orders that used it. Their discount rowCoupon codes track promotion usage and can be single-use or multi-use.- **Single code** — set the `code` attribute on the promotion; `usage_limit` controls how many times it can be redeemed.-- **Multi-code** — bulk-generated codes each track their own state (`unused` / `used`).+- **Multi-code** — bulk-generated codes each track their own state (`unused` / `used`). A code is used up only when an order is placed with it. Applying it to a cart just holds it there, and a shopper who presents a code held by an abandoned cart takes it over, so an unfinished checkout never burns a code.Customers apply codes on the cart via the Store API:diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts/discount_codes_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/discount_codes_controller_spec.rbindex ab9fa293e0..243915cfb5 100644--- a/spree/api/spec/controllers/spree/api/v3/store/carts/discount_codes_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/discount_codes_controller_spec.rb@@ -83,10 +83,11 @@ RSpec.describe Spree::Api::V3::Store::Carts::DiscountCodesController, type: :conexpect(json_response['id']).to start_with('cart_')end- it 'marks the coupon code as used' do+ it 'holds the coupon code for the cart without using it up' dopost :create, params: { cart_id: order.prefixed_id, code: 'multi1' }- expect(coupon_code.reload.state).to eq('used')+ expect(coupon_code.reload.state).to eq('unused')+ expect(coupon_code.cart).to eq(order)endenddiff --git a/spree/core/app/models/spree/coupon_code.rb b/spree/core/app/models/spree/coupon_code.rbindex 759f18ec03..85d6127f0d 100644--- a/spree/core/app/models/spree/coupon_code.rb+++ b/spree/core/app/models/spree/coupon_code.rb@@ -10,6 +10,7 @@ module Spreescope :used_with_code, ->(code) { used.where(code: code.downcase) }scope :with_order, ->(order_id) { where(order_id: order_id) }+ scope :held_by, ->(owner) { owner.is_a?(Spree::Cart) ? where(cart_id: owner.id) : where(order_id: owner.id) }scope :in_promotions, ->(promotion_ids) { where(promotion_id: promotion_ids) }scope :not_in_promotions, ->(promotion_ids) { where.not(promotion_id: promotion_ids) }@@ -38,9 +39,20 @@ module Spreeused_with_code(code).any?end+ # Attaches the code to the cart or order presenting it. The code is not+ # spent here: it stays unused until an order is placed with it, so a code+ # left on an abandoned cart can still be presented by someone else.+ #+ # @param owner [Spree::Cart, Spree::Order]+ # @return [Boolean]def apply_order!(owner)- owner_key = owner.is_a?(Spree::Cart) ? :cart : :order- update(owner_key => owner, state: 'used')+ cart = owner.is_a?(Spree::Cart) ? owner : nil+ update(cart: cart, order: cart ? nil : owner)+ end++ # @return [Spree::Cart, Spree::Order, nil] the record currently holding this code+ def holder+ cart || orderenddef remove_from_orderdiff --git a/spree/core/app/models/spree/promotion.rb b/spree/core/app/models/spree/promotion.rbindex 1a633cef5b..58c7402f5f 100644--- a/spree/core/app/models/spree/promotion.rb+++ b/spree/core/app/models/spree/promotion.rb@@ -317,7 +317,7 @@ module Spreedef code_for_order(order)if multi_codes?- coupon_codes.find_by(order: order)&.code+ coupon_codes.held_by(order).first&.codeelsecodeenddiff --git a/spree/core/app/models/spree/promotion_handler/coupon.rb b/spree/core/app/models/spree/promotion_handler/coupon.rbindex 1e7d1cb1a2..33bc8e7725 100644--- a/spree/core/app/models/spree/promotion_handler/coupon.rb+++ b/spree/core/app/models/spree/promotion_handler/coupon.rb@@ -80,8 +80,7 @@ module Spreeclear_persisted_coupon_code(coupon_code)if promotion.multi_codes?- coupon_code = promotion.coupon_codes.find_by(order: order)- coupon_code&.remove_from_order+ promotion.coupon_codes.held_by(order).first&.remove_from_orderelsepromotion.touchend@@ -217,7 +216,10 @@ module Spreeendif discount || created_line_items- handle_coupon_code(discount, coupon_code) if discount+ if discount && !claim_coupon_code(discount, coupon_code)+ release_coupon_code(order, coupon_code)+ return set_error_code :coupon_code_used+ endorder.recalculate_totals!set_success_code :coupon_code_applied@@ -236,8 +238,53 @@ module Spreeendend- def handle_coupon_code(discount, coupon_code)- Spree::CouponCode.unused.find_by(promotion_id: discount.promotion_id, code: coupon_code)&.apply_order!(order)+ # A single-use code is spent only when an order is placed with it, so a+ # code sitting on another open cart or draft order is taken from it+ # rather than refused: whoever presents it now gets the discount, and+ # whoever places an order first keeps the code. A holder in the middle of+ # checkout keeps it, since its totals are fixed and money may already be+ # at the gateway.+ #+ # The holder is locked before the code, the same order checkout takes+ # them in, so the two serialize instead of deadlocking.+ #+ # @return [Boolean] false when the code can no longer be claimed+ def claim_coupon_code(discount, coupon_code)+ record = Spree::CouponCode.unused.find_by(promotion_id: discount.promotion_id, code: coupon_code)+ return true if record.nil?++ holder = record.holder+ holder = nil if holder && same_record?(holder, order)++ Spree::CouponCode.transaction do+ holder&.lock!+ record.lock!+ next false if record.used? || !same_holder?(record.holder, holder) || checkout_in_progress?(holder)++ release_coupon_code(holder, coupon_code) if holder+ record.apply_order!(order)+ end+ end++ # Gift cards are turned off so a holder paying with one keeps it.+ def release_coupon_code(holder, coupon_code)+ self.class.new(holder, enable_gift_cards: false).remove(coupon_code)+ end++ def checkout_in_progress?(holder)+ case holder+ when Spree::Cart then holder.completed_at.present? || holder.completion_claimed?+ when Spree::Order then holder.completed_at.present? || holder.cart&.completion_claimed? || false+ else false+ end+ end++ def same_record?(holder, other)+ holder.class == other.class && holder.id == other.id+ end++ def same_holder?(current, expected)+ current.nil? || same_record?(current, expected || order)end# Whether the coupon handler should also handle gift card codes.diff --git a/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb b/spree/core/spec/models/spree/promotion_handler/coupon_spec.rbindex 9fcacb3596..980c205aae 100644--- a/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb+++ b/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb@@ -323,7 +323,7 @@ module Spreesubject.applyexpect(subject.success).to be_present- expect(coupon_code.reload).to be_used+ expect(coupon_code.reload).to be_unusedexpect(coupon_code.order).to eq(order)order.line_items.each do |line_item|@@ -350,6 +350,40 @@ module Spreeendend+ context 'when an abandoned cart holds the code' do+ let(:cart) { create(:cart_with_line_items, line_items_count: 3, store: store) }++ before do+ cart.coupon_code = coupon_code.code+ Coupon.new(cart).apply+ end++ it 'moves the code and its discount to the order presenting it' do+ expect(cart.reload.discount_total).to be_negative++ subject.apply++ expect(subject.success).to be_present+ expect(coupon_code.reload).to be_unused+ expect(coupon_code.holder).to eq(order)+ expect(order.reload.total).to eq(100)++ expect(cart.reload.discount_total).to be_zero+ expect(cart.read_attribute(:coupon_code)).to be_nil+ end++ it 'keeps the code on a cart that is checking out' do+ cart.update_columns(completing_at: Time.current)++ subject.apply++ expect(subject.error).to eq Spree.t(:coupon_code_used)+ expect(coupon_code.reload.holder).to eq(cart)+ expect(order.reload.total).to eq(130)+ expect(order.promotions).to be_empty+ end+ end+describe '#remove' dobefore dosubject.apply