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.

Fix: a single-use batch code applied before the cart qualifies is used up by its order (#14762)

Łukasz Adamczyke972766a0018
diff --git a/docs/developer/core-concepts/promotions.mdx b/docs/developer/core-concepts/promotions.mdx
index b7f3d6bef8..b5c477985a 100644
--- a/docs/developer/core-concepts/promotions.mdx
+++ b/docs/developer/core-concepts/promotions.mdx
@@ -215,7 +215,7 @@ Deleting a promotion doesn't disturb the orders that used it. Their discount row
Coupon 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`). 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.
+- **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, even before the cart qualifies, and only the cart holding a code gets its discount. A shopper who presents a code held by an abandoned cart takes it over, so an unfinished checkout never burns a code. The cart that lost it drops the code and gets a `coupon_code_unavailable` warning on its next Store API request that reads or changes the cart, and placing an order with a code that has been taken is refused rather than charged more than the shopper was shown.
Customers apply codes on the cart via the Store API:
diff --git a/docs/plans/6.0-core-rewrite-tasks.md b/docs/plans/6.0-core-rewrite-tasks.md
index 01ba37d61b..bdd7a584e6 100644
--- a/docs/plans/6.0-core-rewrite-tasks.md
+++ b/docs/plans/6.0-core-rewrite-tasks.md
@@ -271,7 +271,7 @@ The point of no return; biggest single wave. Everything before it exists so this
**Finishing work (2026-07-29, post-review autonomous block — scheduled by the delivery-method-rules timing decision):**
- **Fulfillment finishing list DONE:** `Spree::DeliveryMethodStockLocation` model wired (associations + `DeliveryMethod#available_pickup_locations` — configured set, else all pickup-enabled), store pickup_locations endpoint scoped to it + honors `pickup_stock_policy` ('any' offers pickup regardless of local stock), admin API `stock_location_ids` (serializer + params) + dashboard pickup-locations picker (pickup type only, i18n ×6), CSV product import gains `product_type` column (find-or-create per store) with `shipping_category` kept as a labeled-deprecated mapping until the 6.1 drop, `Shipments*` identifier sweep in the order detail page.
- **Delivery-method-rules Phase 1 DONE** (plan `6.0-delivery-method-rules.md`): `spree_delivery_method_rules` table + `Spree::DeliveryMethodRule` STI (ItemTotalRule/WeightRule, preference-schema-driven, registry `Spree.delivery_method_rules` seeded in the engine Environment struct), enforcement via `DeliveryMethod#eligible_for_package?` in the Estimator's method filter (single line — all three entry points covered), FlatRate's four bound preferences carry `deprecated:` warnings, `spree:migrate_calculator_bounds_to_delivery_method_rules` task + manifest step, admin nested `/delivery_methods/:id/rules` CRUD + `/delivery_method_rules/types` discovery + serializer + ability, admin-sdk `deliveryMethods.rules`/`ruleTypes`, dashboard Conditions section in the edit sheet (add/edit/remove rules via PreferencesForm, i18n ×6). Specs: 8/0 model+estimator+data-task, 7/0 API.
-- **Coupon code wired fully (Damian direction):** adjuster candidacy on the PERSISTED cart code (in-memory assignments stay handler-only) with activation/deactivation on recalculation + `order_promotions` join sync; `PromotionHandler::Coupon#remove` clears the persisted code; gift-card branch restores the dirty attribute before locking; store discount_codes POST persists real-but-not-yet-eligible codes (`:coupon_code_not_eligible` → success-with-pending, Shopify parity) and rejects unknown/expired without persisting; cart serializer exposes `coupon_code`. **Orders too:** `spree_orders.coupon_code` column (migration 140001, indexed), copied at completion, on store+admin order serializers, in the ransack whitelist. Order/Cart writers normalize via `super`. Coupon battery 212/0 core + 95/0 api; retry spec covers threshold-crossing activation/deactivation and removal.
+- **Coupon code wired fully (Damian direction):** adjuster candidacy on the PERSISTED cart code (in-memory assignments stay handler-only) with activation/deactivation on recalculation + `order_promotions` join sync; `PromotionHandler::Coupon#remove` clears the persisted code; gift-card branch restores the dirty attribute before locking; store discount_codes POST persists real-but-not-yet-eligible codes (`:coupon_code_not_eligible` → success-with-pending, Shopify parity) and rejects unknown/expired without persisting; cart serializer exposes `coupon_code`. A batch (`multi_codes`) code is held by the cart from the moment it is saved, and candidacy requires that hold — without it one code discounted every cart that saved it (decisions.md 2026-09-29). **Orders too:** `spree_orders.coupon_code` column (migration 140001, indexed), copied at completion, on store+admin order serializers, in the ransack whitelist. Order/Cart writers normalize via `super`. Coupon battery 212/0 core + 95/0 api; retry spec covers threshold-crossing activation/deactivation and removal.
- **Market backfill trimmed to market-only** (`spree:backfill_order_markets`) after Damian's catch — channel_id is already covered by the 5.4→5.5 `channels` manifest step on every upgrade path.
**Docs (T6.5).** SKIPPED per Damian (2026-07-29): `docs/developer` gets a full Spree 6 rewrite separately — no incremental doc edits now. Only CLAUDE.md plan statuses + `docs/plans/*` updated; `docs/api-reference/*.yaml` regenerated (build artifact of the rswag pipeline, not docs work).
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 99b0f0e1a0..ebe19f41c2 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,15 @@
+## 2026-09-29: A batch coupon code is held from the moment it is saved, and discounts only its holder
+
+**Context:** A single-use batch code applied before the cart reached the promotion's minimum was never used up (V-3724). Reproduced on `main`: a $10-off code with a $60 minimum, applied to a $50 cart, answered 201 with `coupon_code_not_eligible`; raising the cart to $100 discounted it and order R1001 was placed at $95.00, while the code still read `unused` with no order. A second guest then applied the same code and got the discount too (R1002), two guests who both saved a code below the minimum both placed discounted orders (R1003, R1004), and a guest who saved a code another cart already held was discounted alongside it (R1005, R1006). The cause is a gap between two decisions. The 2026-07-29 coupon wiring saves a real but not-yet-eligible code on the cart and lets recalculation activate it, and the V-3680 fix (7335a712f1) moved "hold the code on the cart" into the handler's claim, which runs only when the code applies straight away. Recalculation activated the saved code from its text alone (`Adjusters::Promotion#coupon_promotions`), so no code record was ever held, and completion spends only the codes the cart holds. Separately, a saved code that had not applied yet could not be removed: `DELETE /carts/:id/discount_codes/:code` answered 422 "doesn't exist", because removal looked only at promotions already attached to the cart.
+
+**Decision:** Saving a code keeps its Shopify-parity retry, and the code record carries the rule. `PromotionHandler::Coupon` claims a batch code before anything prices it, including when the cart does not qualify yet, so the takeover rules from V-3680 apply unchanged: an open cart gives the code up to whoever presents it, and a cart in checkout or a draft order keeps it. `Promotion#eligible?` answers false for a batch-code promotion unless the cart or order holds one of its codes, so the adjuster never discounts a non-holder, whichever way the promotion arrived — attached, saved code or being activated — and the other eligibility callers (the free-shipping handler, the gift action's revert) follow the same rule. A cart or order holds only the codes it shows: every apply gives back any other batch code it holds whose promotion is not attached, so a replaced or mistyped code does not leave a hold behind that is later spent with the order, and `Orders::Create`, which drops a code that does not qualify yet, gives that code back too. A cart that loses its code keeps the text it entered, so the next Store API request that reads or changes the cart removes it and carries a `coupon_code_unavailable` warning. Writes sweep as well as reads, unlike the out-of-stock sweep, since API clients may rely on write responses alone; each endpoint sweeps before it renders, as the line sweep does. Checkout refuses, with the same code, a cart showing a batch code it does not hold (used, taken by another cart or order, or given back by one), rather than placing it at a higher total than the shopper last saw or naming on the order a code it never used. Removing a saved code that has not applied yet now succeeds and gives the hold back. Product calls settled with the maintainer: takeover also applies to a cart still below the minimum, the losing shopper is warned, and checkout is refused rather than placed at full price.
+
+Rejected: refusing codes that do not qualify yet, which would reverse the 2026-07-29 decision for the storefront and for draft orders; and claiming the code inside the adjuster when it first writes a discount, which would take locks and release other carts from inside a recalculation.
+
+**Consequences:** A shopper who saves a batch code below the minimum now blocks nobody. Anyone presenting it takes it over, as with any held code. A takeover recalculates the losing cart at once, so the checkout refusal is what that shopper sees only if they place the order with no other cart request in between. A code saved on a cart before this change is held by nobody, so that cart's next response drops it with the same warning even though the code is free; the shopper can enter it again. Orders already placed on the affected builds keep their discount, because placed orders never re-run promotions. Their codes still read `unused`, but `spree_orders.coupon_code` records which code each used, so they can be found. No backfill ships. Left alone, both pre-existing: every checkout refusal that carries a code (`payment_failed`, `cart_changed`, now `coupon_code_unavailable`) reaches the Store API as the error hash's text rather than its message; and a single-code promotion's `usage_limit` counts placed orders only, so open carts can pass it together (not tested).
+
+**Plans amended:** `6.0-core-rewrite-tasks.md` (the "Coupon code wired fully" bullet).
+
## 2026-09-25: Replacement units are flagged, so an order edit counts only what was bought
**Context:** Raising the quantity of an exchanged line on a placed order deleted the line's original fulfillment and its delivery charge (V-3707). Reproduced on `main`: order R1001, one Stainless kettle at $79.99 plus $5.00 Standard delivery, exchanged for Matte Black; raising the line to 2 answered 200, deleted the $5.00 fulfillment with its Stainless unit, took `delivery_total` from 5.0 to 0.0, and released the Stainless allocation instead of adding one. There were two causes. `Exchanges::Fulfill` and `Claims::Resolve` built their replacement units through `order.fulfillment_items.new`; the stock coordinator packs a copy of each, and the order's next save persisted the original as well, so every replacement left a second unit on the line with no fulfillment. `Spree::OrderInventory#verify` then counted every unit on the line against its quantity, found three units for a quantity of two, and removed the one it could reach, the original. With the stray unit gone the edit still added nothing, because the replacement counted as a unit the line already held. The 6.0 returns rebuild had removed `exchanged_unit?` and `original_return_item`, so nothing told a replacement apart from a unit the customer bought.
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb b/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb
index 033bb5cd8d..4a47ea78c2 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb
@@ -57,6 +57,13 @@ module Spree
@cart = @cart.remove_out_of_stock_items!
end
+ # Drops a batch coupon code the cart no longer holds. Unlike the line
+ # sweep this runs after writes too, since an API client may rely on
+ # write responses alone to learn why its discount went.
+ def sweep_unavailable_coupon_code!
+ @cart = @cart.remove_unavailable_coupon_code!
+ end
+
# Render what the checkout produced (for the complete action).
#
# A checkout spanning several sellers produced a group of orders rather
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/fulfillments_controller.rb
index f09cce5b1a..e297a71cf9 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts/fulfillments_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/fulfillments_controller.rb
@@ -36,6 +36,7 @@ module Spree
recalculate
+ sweep_unavailable_coupon_code!
render_cart
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts/gift_cards_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/gift_cards_controller.rb
index 673d1a1fc6..87adf4cc30 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts/gift_cards_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/gift_cards_controller.rb
@@ -18,6 +18,7 @@ module Spree
result = @cart.apply_gift_card(gift_card)
if result.success?
+ sweep_unavailable_coupon_code!
render_cart(status: :created)
else
render_service_error(result.error)
@@ -31,6 +32,7 @@ module Spree
result = @cart.remove_gift_card
if result.success?
+ sweep_unavailable_coupon_code!
render_cart
else
render_service_error(result.error)
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb
index 5e3770a327..85eafddb8b 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb
@@ -21,6 +21,7 @@ module Spree
)
if result.success?
+ sweep_unavailable_coupon_code!
render_cart(status: :created)
else
render_result_error(result)
@@ -56,6 +57,7 @@ module Spree
)
if result.success?
+ sweep_unavailable_coupon_code!
render_cart
else
render_result_error(result)
@@ -67,6 +69,7 @@ module Spree
@line_item.update!(metadata: @line_item.metadata.merge(permitted_params[:metadata].to_h))
end
+ sweep_unavailable_coupon_code!
render_cart
end
end
@@ -83,6 +86,7 @@ module Spree
)
if result.success?
+ sweep_unavailable_coupon_code!
render_cart
else
render_result_error(result)
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb
index 3f6f0c98ef..b595318657 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb
@@ -19,6 +19,7 @@ module Spree
)
if result.success?
+ sweep_unavailable_coupon_code!
render_cart
else
render_service_error(result.error)
@@ -32,6 +33,7 @@ module Spree
result = Spree.store_credit_remove_service.call(order: @cart)
if result.success?
+ sweep_unavailable_coupon_code!
render_cart
else
render_service_error(result.error)
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
index 30f9d3242e..f6e2e883f4 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
@@ -32,6 +32,7 @@ module Spree
# The customer is returning to a cart that may have sat for days.
sweep_unbuyable_lines!
+ sweep_unavailable_coupon_code!
render_cart
end
@@ -70,6 +71,7 @@ module Spree
)
if result.success?
+ sweep_unavailable_coupon_code!
render_cart
else
render_service_error(result.error, code: ERROR_CODES[:validation_error])
@@ -107,6 +109,7 @@ module Spree
if result.success?
# Signing in hands back a cart built earlier, possibly long ago.
sweep_unbuyable_lines!
+ sweep_unavailable_coupon_code!
render_cart
else
render_service_error(result.error.to_s)
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.rb
index 243915cfb5..029ee6e2d7 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
@@ -68,6 +68,32 @@ RSpec.describe Spree::Api::V3::Store::Carts::DiscountCodesController, type: :con
expect(warning['code']).to eq('coupon_code_not_eligible')
expect(warning['message']).to be_present
end
+
+ context 'from a batch of single-use codes' do
+ let!(:promotion) do
+ create(:promotion_with_item_total_rule, :with_line_item_adjustment,
+ code: nil, multi_codes: true, number_of_codes: 1, kind: :coupon_code, store: store,
+ item_total_threshold_amount: 1_000_000)
+ end
+ let(:coupon_code) { promotion.coupon_codes.first }
+
+ it 'holds the code for the cart' do
+ post :create, params: { cart_id: order.prefixed_id, code: coupon_code.code }
+
+ expect(response).to have_http_status(:created)
+ expect(coupon_code.reload.holder).to eq(order)
+ end
+
+ it 'refuses a code a cart in checkout holds' do
+ coupon_code.update!(cart: create(:cart, store: store, completing_at: Time.current))
+
+ post :create, params: { cart_id: order.prefixed_id, code: coupon_code.code }
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['message']).to eq(Spree.t(:coupon_code_used))
+ expect(order.reload.read_attribute(:coupon_code)).to be_nil
+ end
+ end
end
context 'with a multi-code promotion' do
diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb
index df1e66e0f3..231e0b704b 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb
@@ -25,6 +25,19 @@ RSpec.describe Spree::Api::V3::Store::Carts::ItemsController, type: :controller
expect(json_response['total_quantity']).to eq(2)
end
+ it 'drops a batch coupon code another cart has taken, with a warning' do
+ promotion = create(:promotion, :with_line_item_adjustment, code: nil, multi_codes: true, number_of_codes: 1, kind: :coupon_code, store: store)
+ coupon_code = promotion.coupon_codes.first
+ coupon_code.update!(cart: create(:cart, store: store))
+ order.update_columns(coupon_code: coupon_code.code)
+
+ post :create, params: { cart_id: order.prefixed_id, variant_id: variant.prefixed_id, quantity: 2 }
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['coupon_code']).to be_nil
+ expect(json_response['warnings'].map { |warning| warning['code'] }).to include('coupon_code_unavailable')
+ end
+
it 'defaults quantity to 1' do
post :create, params: { cart_id: order.prefixed_id, variant_id: variant.prefixed_id }
diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
index 7c4edb3be0..89954545cd 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
@@ -504,6 +504,20 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller do
expect(json_response['items'].length).to eq(original_item_count - 1)
end
+
+ it 'drops a batch coupon code another cart has taken, with a warning' do
+ promotion = create(:promotion, :with_line_item_adjustment, code: nil, multi_codes: true, number_of_codes: 1, kind: :coupon_code, store: store)
+ coupon_code = promotion.coupon_codes.first
+ coupon_code.update!(cart: create(:cart, store: store))
+ cart.update_columns(coupon_code: coupon_code.code)
+
+ get :show, params: { id: cart.prefixed_id }
+
+ expect(json_response['coupon_code']).to be_nil
+ expect(json_response['warnings']).to contain_exactly(
+ 'code' => 'coupon_code_unavailable', 'message' => Spree.t(:coupon_code_unavailable)
+ )
+ end
end
context 'auto-advance' do
diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rb
index 437e804cd8..2167b47352 100644
--- a/spree/core/app/models/spree/cart.rb
+++ b/spree/core/app/models/spree/cart.rb
@@ -284,5 +284,43 @@ module Spree
cart
end
+ # Whether this cart shows a batch coupon code it does not hold — used,
+ # taken by another cart or order, or given up by one — and so can never
+ # discount it.
+ #
+ # @return [Boolean]
+ def coupon_code_unavailable?
+ code = read_attribute(:coupon_code)
+ return false if code.blank?
+
+ record = Spree::CouponCode.where(promotion_id: store.promotions.select(:id)).find_by(code: code)
+ record.present? && record.cart_id != id
+ end
+
+ # Drops an entered batch coupon code this cart no longer holds, and warns
+ # the shopper, who otherwise sees the discount vanish.
+ #
+ # @return [Spree::Cart]
+ def remove_unavailable_coupon_code!
+ return self unless coupon_code_unavailable?
+
+ # The lock refuses unsaved attributes and reloads the cart, so this
+ # request's warnings are set aside and put back.
+ existing_warnings = warnings
+ clear_attribute_changes([:warnings])
+ removed = with_lock do
+ # Checked under the lock, as the completion claim itself is: a
+ # completing cart's code sits on its draft order while the payment
+ # runs, and a failed payment hands it back.
+ next false if completion_claimed? || !coupon_code_unavailable?
+
+ Spree.coupon_handler.new(self, enable_gift_cards: false).remove(read_attribute(:coupon_code))
+ true
+ end
+ self.warnings = existing_warnings
+ self.warnings |= [{ code: 'coupon_code_unavailable', message: Spree.t(:coupon_code_unavailable) }] if removed
+ self
+ end
+
end
end
diff --git a/spree/core/app/models/spree/promotion.rb b/spree/core/app/models/spree/promotion.rb
index d6fe3cf364..03759a44f1 100644
--- a/spree/core/app/models/spree/promotion.rb
+++ b/spree/core/app/models/spree/promotion.rb
@@ -111,7 +111,8 @@ module Spree
# exact recalculation where the cart first qualifies, and deactivates the
# same way (Shopify-parity for cart-level discount codes). In-memory
# assignments deliberately don't participate: unsaved codes belong to
- # the explicit PromotionHandler::Coupon path.
+ # the explicit PromotionHandler::Coupon path. A batch code counts only
+ # while the purchase holds it (see #eligible?).
#
# @param purchase [Spree::Cart, Spree::Order]
# @return [Array<Spree::Promotion>] empty, or the one promotion
@@ -223,7 +224,7 @@ module Spree
# called anytime order.recalculate_totals! happens
def eligible?(promotable, options = {})
- return false if expired? || usage_limit_exceeded?(promotable) || blacklisted?(promotable)
+ return false if expired? || usage_limit_exceeded?(promotable) || blacklisted?(promotable) || !code_held_by?(promotable)
!!eligible_rules(promotable, options)
end
@@ -346,6 +347,13 @@ module Spree
private
+ # A batch code discounts only the cart or order holding it, which is what
+ # keeps each generated code to a single order. A cart's line item has no
+ # order, and the adjuster has asked with the cart before pricing its lines.
+ def code_held_by?(order)
+ !multi_codes? || order.nil? || coupon_codes.held_by(order).exists?
+ end
+
# Counts distinct checkouts behind a set of discount rows.
#
# An order placed on its own is one checkout; the several orders a split
diff --git a/spree/core/app/models/spree/promotion_handler/coupon.rb b/spree/core/app/models/spree/promotion_handler/coupon.rb
index 0d0899eb50..21666da283 100644
--- a/spree/core/app/models/spree/promotion_handler/coupon.rb
+++ b/spree/core/app/models/spree/promotion_handler/coupon.rb
@@ -57,9 +57,25 @@ module Spree
else
set_error_code :coupon_code_not_found
end
+ release_stale_coupon_codes
self
end
+ # Gives back every batch code this cart or order holds but no longer
+ # shows: anything other than the code it entered while that code waits
+ # to qualify, or the codes of promotions attached to it. Without this a
+ # replaced or dropped code stays held, and is spent with the order.
+ #
+ # @return [void]
+ def release_stale_coupon_codes
+ return unless order.persisted?
+
+ stale = Spree::CouponCode.unused.held_by(order).where.not(promotion_id: order.promotions.select(:id))
+ pending = order.coupon_code.to_s.downcase.presence if status_code == :coupon_code_not_eligible
+ stale = stale.where.not(code: pending) if pending
+ stale.find_each(&:remove_from_order)
+ end
+
def remove(coupon_code)
if gift_cards_enabled? && order.gift_card
result = order.remove_gift_card
@@ -75,19 +91,13 @@ module Spree
promotion = order.promotions.with_coupon_code(coupon_code)
if promotion.present?
- # Order promotion has to be destroyed before line item removing
- order.promotions.delete(promotion)
clear_persisted_coupon_code(coupon_code)
+ detach_promotion(promotion)
- if promotion.multi_codes?
- promotion.coupon_codes.held_by(order).first&.remove_from_order
- else
- promotion.touch
- end
-
- remove_promotion_adjustments(promotion)
- remove_promotion_line_items(promotion)
- order.recalculate_totals!
+ set_success_code :adjustments_deleted
+ elsif clear_persisted_coupon_code(coupon_code)
+ # Saved before the cart qualified, so no promotion is attached yet.
+ Spree::CouponCode.held_by(order).find_by(code: coupon_code.to_s.strip.downcase)&.remove_from_order
set_success_code :adjustments_deleted
else
@@ -96,6 +106,18 @@ module Spree
self
end
+ # Gives the code up to another cart or order that has taken it. Unlike
+ # #remove, the entered code stays on this one, so the shopper can be
+ # told it went (Spree::Cart#remove_unavailable_coupon_code!).
+ #
+ # @param coupon_code [String]
+ # @return [self]
+ def release(coupon_code)
+ promotion = order.promotions.with_coupon_code(coupon_code)
+ detach_promotion(promotion) if promotion.present?
+ self
+ end
+
def set_success_code(code)
@status_code = code
@success = Spree.t(code)
@@ -143,6 +165,21 @@ module Spree
order.update_column(:coupon_code, nil)
end
+ def detach_promotion(promotion)
+ # Order promotion has to be destroyed before line item removing
+ order.promotions.delete(promotion)
+
+ if promotion.multi_codes?
+ promotion.coupon_codes.held_by(order).first&.remove_from_order
+ else
+ promotion.touch
+ end
+
+ remove_promotion_adjustments(promotion)
+ remove_promotion_line_items(promotion)
+ order.recalculate_totals!
+ end
+
def remove_promotion_adjustments(promotion)
order.discounts.where(promotion_action_id: promotion.actions.pluck(:id)).destroy_all
end
@@ -165,6 +202,11 @@ module Spree
return set_error_code :coupon_code_used if promotion.coupon_codes.used.where(code: order.coupon_code).exists?
return promotion_usage_limit_exceeded if promotion.usage_limit_exceeded?(order)
+ # Claimed before anything prices the code, since the adjuster only
+ # discounts the holder, and a cart that qualifies later activates the
+ # code on recalculation without coming back here.
+ return set_error_code :coupon_code_used unless claim_coupon_code(order.coupon_code.downcase)
+
unless promotion.eligible?(order, options)
# Rules that explain themselves keep their message, but the status
# code is always :coupon_code_not_eligible so callers can park the
@@ -216,11 +258,6 @@ module Spree
end
if discount || created_line_items
- if discount && !claim_coupon_code(discount, coupon_code)
- release_coupon_code(order, coupon_code)
- return set_error_code :coupon_code_used
- end
-
order.recalculate_totals!
set_success_code :coupon_code_applied
elsif order.promotions.with_coupon_code(order.coupon_code)
@@ -249,8 +286,8 @@ module Spree
# 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.find_by(promotion_id: discount.promotion_id, code: coupon_code)
+ def claim_coupon_code(coupon_code)
+ record = promotion.coupon_codes.find_by(code: coupon_code)
return true if record.nil?
holder = record.holder
@@ -261,16 +298,11 @@ module Spree
record.lock!
next false if record.used? || !same_holder?(record.holder, holder) || !releasable?(holder)
- release_coupon_code(holder, coupon_code) if holder
+ self.class.new(holder).release(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 releasable?(holder)
return true if holder.nil?
diff --git a/spree/core/app/services/spree/orders/create.rb b/spree/core/app/services/spree/orders/create.rb
index f4b5a24027..27460456e6 100644
--- a/spree/core/app/services/spree/orders/create.rb
+++ b/spree/core/app/services/spree/orders/create.rb
@@ -170,6 +170,7 @@ module Spree
coupon_code: @params[:coupon_code]
}
order.coupon_code = nil
+ handler.release_stale_coupon_codes
end
end
end
diff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rb
index d94d2925c9..e6a9ade936 100644
--- a/spree/core/app/workflows/spree/carts/complete.rb
+++ b/spree/core/app/workflows/spree/carts/complete.rb
@@ -47,6 +47,7 @@ module Spree
cart.with_lock do
step :guard_concurrent_completion
+ step :guard_coupon_code
step :recalculate_in_lock
step :verify_expected_total
step :validate_cart
@@ -113,6 +114,15 @@ module Spree
failure(cart, code: 'completion_in_progress') if cart.completion_claimed?
end
+ # A batch code this cart no longer holds no longer discounts it, so the
+ # shopper would be charged more than the total they last saw, and the
+ # order would name a code it never used.
+ def guard_coupon_code
+ return unless cart.coupon_code_unavailable?
+
+ failure(cart, code: 'coupon_code_unavailable', message: Spree.t(:coupon_code_unavailable))
+ end
+
# In-lock recalculation — the totals about to be charged are computed
# here, not trusted from earlier requests.
# Only external pricing is re-confirmed: Spree's own catalog is read
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 744bc78017..f0cfe631a3 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -882,6 +882,7 @@ en:
coupon_code_max_usage: Coupon code usage limit exceeded
coupon_code_not_eligible: This coupon code is not eligible for this order
coupon_code_not_found: The coupon code you entered doesn't exist. Please try again.
+ coupon_code_unavailable: The coupon code on your cart is no longer available.
coupon_code_unknown_error: This coupon code could not be applied to the cart at this time.
coupon_code_used: The coupon code you entered has already been used. Please try again.
coupon_codes: Coupon codes
diff --git a/spree/core/spec/models/spree/adjusters/coupon_code_retry_spec.rb b/spree/core/spec/models/spree/adjusters/coupon_code_retry_spec.rb
index 5eb30d5ffe..7e60a365c1 100644
--- a/spree/core/spec/models/spree/adjusters/coupon_code_retry_spec.rb
+++ b/spree/core/spec/models/spree/adjusters/coupon_code_retry_spec.rb
@@ -47,4 +47,88 @@ describe 'coupon code retry on recalculation' do
expect(cart.reload.read_attribute(:coupon_code)).to be_nil
expect(cart.discounts.where(promotion_id: promotion.id)).to be_empty
end
+
+ context 'with a batch of single-use codes' do
+ let!(:promotion) do
+ create(:promotion_with_item_total_rule, :with_order_adjustment,
+ code: nil, multi_codes: true, number_of_codes: 2, kind: :coupon_code, store: store,
+ item_total_threshold_amount: 30, weighted_order_adjustment_amount: 5)
+ end
+ let(:coupon_code) { promotion.coupon_codes.first }
+ let(:other_cart) { create(:cart_with_line_items, store: store, line_items_price: 10) }
+
+ def apply_code(owner)
+ owner.update!(coupon_code: coupon_code.code)
+ Spree::PromotionHandler::Coupon.new(owner).apply
+ end
+
+ def qualify(owner)
+ create(:line_item, cart: owner, order: nil, price: 25)
+ owner.line_items.reload
+ owner.recalculate_totals!
+ end
+
+ it 'holds a code saved before the cart qualifies' do
+ expect(apply_code(cart).status_code).to eq(:coupon_code_not_eligible)
+ expect(coupon_code.reload.holder).to eq(cart)
+
+ qualify(cart)
+
+ expect(cart.reload.discount_total).to eq(-5)
+ end
+
+ it 'discounts only the cart that presented the code last' do
+ apply_code(cart)
+ apply_code(other_cart)
+
+ qualify(cart)
+ qualify(other_cart)
+
+ expect(coupon_code.reload.holder).to eq(other_cart)
+ expect(cart.reload.discount_total).to be_zero
+ expect(other_cart.reload.discount_total).to eq(-5)
+ end
+
+ it 'never discounts a cart saving the code without holding it' do
+ cart.update!(coupon_code: coupon_code.code)
+
+ qualify(cart)
+
+ expect(cart.reload.discount_total).to be_zero
+ end
+
+ it 'gives back a code saved before the cart qualified once another replaces it' do
+ apply_code(cart)
+ replacement = promotion.coupon_codes.second
+ cart.update!(coupon_code: replacement.code)
+ Spree::PromotionHandler::Coupon.new(cart).apply
+
+ expect(coupon_code.reload.holder).to be_nil
+ expect(replacement.reload.holder).to eq(cart)
+ end
+
+ it 'treats a saved code the cart does not hold as unavailable, whoever holds it' do
+ apply_code(cart)
+
+ expect(cart.coupon_code_unavailable?).to be(false)
+
+ coupon_code.update!(cart: other_cart)
+
+ expect(cart.coupon_code_unavailable?).to be(true)
+
+ coupon_code.remove_from_order
+
+ expect(cart.coupon_code_unavailable?).to be(true)
+ end
+
+ it 'lets the shopper remove a code saved before the cart qualified' do
+ apply_code(cart)
+
+ handler = Spree::PromotionHandler::Coupon.new(cart).remove(coupon_code.code)
+
+ expect(handler.successful?).to be(true)
+ expect(cart.reload.read_attribute(:coupon_code)).to be_nil
+ expect(coupon_code.reload.holder).to be_nil
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb b/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
index 19de1579bb..e81cdfbf65 100644
--- a/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
+++ b/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
@@ -369,7 +369,31 @@ module Spree
expect(order.reload.total).to eq(100)
expect(cart.reload.discount_total).to be_zero
+ expect(cart.promotions).to be_empty
+ end
+
+ it 'tells the cart that lost the code on its next read' do
+ subject.apply
+ cart.reload.warnings = [{ code: 'line_item_removed' }]
+
+ cart.remove_unavailable_coupon_code!
+
expect(cart.read_attribute(:coupon_code)).to be_nil
+ expect(cart.warnings).to contain_exactly(
+ { code: 'line_item_removed' },
+ { code: 'coupon_code_unavailable', message: Spree.t(:coupon_code_unavailable) }
+ )
+ end
+
+ it 'leaves the code alone while the cart is completing' do
+ cart.reload.update_columns(completing_at: Time.current)
+ Spree::CouponCode.where(cart_id: cart.id).update_all(order_id: order.id, cart_id: nil)
+
+ cart.remove_unavailable_coupon_code!
+
+ expect(cart.read_attribute(:coupon_code)).to eq(coupon_code.code)
+ expect(cart.discount_total).to be_negative
+ expect(cart.warnings).to be_empty
end
it 'keeps the code on a cart that is checking out' do
diff --git a/spree/core/spec/models/spree/promotion_handler/free_shipping_spec.rb b/spree/core/spec/models/spree/promotion_handler/free_shipping_spec.rb
index 2027b43a32..6291bb9ad1 100644
--- a/spree/core/spec/models/spree/promotion_handler/free_shipping_spec.rb
+++ b/spree/core/spec/models/spree/promotion_handler/free_shipping_spec.rb
@@ -39,6 +39,7 @@ module Spree
let!(:action) { Spree::Promotion::Actions::FreeShipping.create(promotion: promotion) }
it 'does adjust the shipment when applied to order' do
+ promotion.coupon_codes.first.apply_order!(order)
order.promotions << promotion
expect { subject.activate }.to change { shipment.discounts.count }
@@ -47,6 +48,12 @@ module Spree
it 'does not adjust the shipment when not applied to order' do
expect { subject.activate }.not_to change { shipment.discounts.count }
end
+
+ it 'does not adjust the shipment when the order does not hold a code' do
+ order.promotions << promotion
+
+ expect { subject.activate }.not_to change { shipment.discounts.count }
+ end
end
context 'if promo has a path' do
diff --git a/spree/core/spec/services/spree/orders/create_spec.rb b/spree/core/spec/services/spree/orders/create_spec.rb
index a2e6d944a7..95b5ce3a91 100644
--- a/spree/core/spec/services/spree/orders/create_spec.rb
+++ b/spree/core/spec/services/spree/orders/create_spec.rb
@@ -186,6 +186,29 @@ module Spree
end
end
+ context 'with a batch coupon code the order does not qualify for yet' do
+ let!(:promotion) do
+ create(:promotion_with_item_total_rule, :with_order_adjustment,
+ code: nil, multi_codes: true, number_of_codes: 1, kind: :coupon_code, store: store,
+ item_total_threshold_amount: 1_000)
+ end
+ let(:coupon_code) { promotion.coupon_codes.first }
+
+ let(:params) do
+ {
+ email: '[email protected]',
+ items: [{ variant_id: variant.prefixed_id, quantity: 1 }],
+ coupon_code: coupon_code.code
+ }
+ end
+
+ it 'leaves the code free for others' do
+ expect(subject).to be_success
+ expect(subject.value.read_attribute(:coupon_code)).to be_nil
+ expect(coupon_code.reload.holder).to be_nil
+ end
+ end
+
context 'with an automatic free-shipping promotion (no coupon code)' do
let!(:promotion) do
create(:free_shipping_promotion, kind: :automatic)
diff --git a/spree/core/spec/workflows/spree/carts/complete_spec.rb b/spree/core/spec/workflows/spree/carts/complete_spec.rb
index 3192c46a3d..b48b8e778a 100644
--- a/spree/core/spec/workflows/spree/carts/complete_spec.rb
+++ b/spree/core/spec/workflows/spree/carts/complete_spec.rb
@@ -610,6 +610,33 @@ module Spree
expect(coupon_code.reload.state).to eq('unused')
expect(coupon_code.order_id).to be_nil
end
+
+ it 'refuses a cart discounted by a code another cart has since taken' do
+ promotion = create(:promotion_with_item_adjustment, adjustment_rate: 2, kind: :coupon_code, store: store, multi_codes: true, number_of_codes: 1)
+ coupon_code = promotion.coupon_codes.first
+ coupon_code.update!(cart: ready_cart)
+ ready_cart.update_columns(coupon_code: coupon_code.code)
+ ready_cart.recalculate_totals!
+ coupon_code.update!(cart: create(:cart, store: store))
+
+ result = described_class.call(cart: ready_cart)
+
+ expect(result).to be_failure
+ expect(result.error.value[:code]).to eq('coupon_code_unavailable')
+ expect(ready_cart.reload.order).to be_nil
+ expect(ready_cart.discounts.where(promotion_id: promotion.id)).to be_present
+ end
+
+ it 'refuses a cart showing a code it gave up, rather than naming it on the order' do
+ promotion = create(:promotion_with_item_adjustment, adjustment_rate: 2, kind: :coupon_code, store: store, multi_codes: true, number_of_codes: 1)
+ ready_cart.update_columns(coupon_code: promotion.coupon_codes.first.code)
+
+ result = described_class.call(cart: ready_cart)
+
+ expect(result).to be_failure
+ expect(result.error.value[:code]).to eq('coupon_code_unavailable')
+ expect(ready_cart.reload.order).to be_nil
+ end
end
end
end