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: free gifts counting toward other promotions' spend thresholds and percentages (#14761)

Łukasz Adamczyk4be2e54343bf
diff --git a/docs/developer/core-concepts/promotions.mdx b/docs/developer/core-concepts/promotions.mdx
index 2a10ae6690..b7f3d6bef8 100644
--- a/docs/developer/core-concepts/promotions.mdx
+++ b/docs/developer/core-concepts/promotions.mdx
@@ -94,7 +94,7 @@ Rules decide when a promotion is eligible. You can combine multiple rules and co
| Rule | Applies when |
|---|---|
| **FirstOrder** | It's the customer's first order (checked by account and email) |
-| **ItemTotal** | The order subtotal is within configured minimum/maximum thresholds |
+| **ItemTotal** | The order subtotal, not counting free gifts, is within configured minimum/maximum thresholds |
| **Product** | Specific products are in the order (`any` / `all` / `none` match policy) |
| **Category** | Products from specific categories are in the order — child categories count |
| **OptionValue** | Products with specific option values (size, color) are in the order |
@@ -141,6 +141,8 @@ Adds specified products to the cart when the promotion is eligible, checking sto
No second action is needed to make the gift free — pairing this with an order discount set to the gift's price discounts it twice.
+A gift the promotion gives away does not count toward what other promotions measure: it cannot lift an order over an `ItemTotal` threshold, and an order discount's percentage is taken from the paid goods only. Nor does it count toward its own promotion's threshold, so in "Spend \$100 get a free sample" the sample is taken back once the paid goods drop to \$100 or less. A copy of the gift the customer pays for counts toward other promotions like any other item, but not toward its own promotion's threshold.
+
**Use case:** "Free gift with purchase", "Spend $100 get a free sample".
## Managing Promotions
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
index 2033827419..fbb7169855 100644
--- a/docs/developer/upgrades/5.6-to-6.0.mdx
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -401,6 +401,8 @@ The `Create line items` promotion action now discounts the items it adds down to
Two further changes come with it. A customer who already has the gift variant in their cart now gets theirs free rather than a second copy being added, and the promotion applies where it previously did nothing at all. And a gift is only taken back out of the cart for promotions actually applied to that order, so a customer who bought the gift variant themselves without qualifying keeps it.
+A gift also no longer counts toward spend thresholds or toward the amount a percentage-off order discount is taken from. That includes the gift promotion's own threshold, so a "spend over a set amount, get a gift" promotion now takes the gift back once the paid items fall below the threshold.
+
## Dependency injection changes
6.0 introduces `*_workflow` keys for the flows that graduated to the workflow tier. The old `*_service` keys **stay settable and readable one release so applications don't crash at boot — but a legacy write is stashed, not applied**: a class written against the old service contract is not interchangeable with the workflow the new call sites consume. Reads return your stashed class (legacy code calling its own override keeps working), falling back to the workflow. Removed in 6.1.
diff --git a/docs/plans/6.0-6.1-split-adjustments.md b/docs/plans/6.0-6.1-split-adjustments.md
index 798aa72433..e35ac06e75 100644
--- a/docs/plans/6.0-6.1-split-adjustments.md
+++ b/docs/plans/6.0-6.1-split-adjustments.md
@@ -195,7 +195,7 @@ Columns beyond the FKs: `amount` (≤ 0), `label`, `kind` (`'promotion'`, `'manu
**FreeShipping** writes a `Discount` on the fulfillment (`amount = -cost`) and persists the row **even at zero amount** — `Order#has_free_shipping?` tests row existence; the zero-skip pattern used elsewhere does not apply to this action.
-**CreateLineItems** writes a line-level `Discount` covering the gifted units of the line it adds (`amount = -price * gifted_quantity`), so the gift costs nothing without a second action paying for it. It is the one action whose discount the promotion's rules do not narrow: the gift is rarely the product the rules name, so the rules decide whether the promotion applies and the action decides which line it pays for, through `PromotionAction#applies_to_line_item?`.
+**CreateLineItems** writes a line-level `Discount` covering the gifted units of the line it adds (`amount = -price * gifted_quantity`), so the gift costs nothing without a second action paying for it. It is the one action whose discount the promotion's rules do not narrow: the gift is rarely the product the rules name, so the rules decide whether the promotion applies and the action decides which line it pays for, through `PromotionAction#applies_to_line_item?`. The gift keeps its price on its line, so what promotions measure takes it out: the `ItemTotal` rule compares `item_total - gift_amount` and order-level calculators read the purchase's `amount`, which is net of gifts. `Spree::Purchase::Totals#gift_amount` counts a gift only while its promotion gives it (`CreateLineItems#gives_away?`), and a gift promotion's own gift never counts toward its own threshold, so a gift cannot keep its own offer alive.
### Fee (extensible, taxable)
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 1504134815..ffe5d01124 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,15 @@
+## 2026-09-25: A free gift does not count toward what other promotions measure
+
+**Context:** The 2026-09-23 fix left the gift at its list price on its line and paid for it with a discount. Everything that measures the cart for promotions sums list prices, so the gift counted in full: 2 x $49.99 of paid goods plus a $49.99 gift passed a "spend over $100, 10% off" promotion, which took $15.00 and left the shopper paying $84.98 where $99.98 was owed, and with three paid units the 10% came to $20.00 instead of $15.00 (V-3710). A gift promotion with its own spend threshold was worse: its gift kept the cart over the threshold after the shopper dropped below it, so the same one-kettle cart cost $49.00 after starting at two and $60.00 when built fresh.
+
+**Decision:** Free gifts are taken out of what promotions measure; every other line still counts at its list price, so a product sale still counts toward a spend threshold as before. `Spree::Purchase::Totals#gift_amount` is the one measure: the `ItemTotal` rule compares `item_total - gift_amount`, and `#amount`, which order-level calculators read, is net of it. A gift counts as given only while its promotion gives it (`CreateLineItems#gives_away?`, the same eligibility and "qualifies beyond the gift" test its discount uses), so a copy the shopper pays for still counts toward other promotions. A promotion's own gifts are always taken out of its own threshold, paid copy included, since the gift cannot be what qualifies the promotion giving it away. Deciding whether another promotion gives its gift is judged one level deep, through a new `own_gift_only: true` rule option, so two gift promotions with spend thresholds cannot each wait on the other. Other promotions' gifts are looked for among the promotions a recalculation writes discounts for - those the purchase carries, plus the one its saved coupon code names (`Spree::Promotion.held_by_saved_coupon_code`, moved out of `Adjusters::Promotion` so both read it) - so a gift leaves the measure exactly when its discount can be written. Looking among the store's automatic promotions instead let an eligible but not yet applied gift promotion take a gift the shopper was still paying for out of another promotion's threshold. The cost of the narrower set: adding the gift recalculates the cart before its promotion is linked, so a spend promotion can qualify in that moment and stay linked at $0.00 once the gift is taken out. It is listed at $0.00 in the Store and Admin API discount lists, counts as "used" for the delete guard, and uses none of the promotion's limit, which counts discount rows; links never being removed is the older behaviour behind it and is left to its own issue.
+
+Rejected: subtracting every line-level discount, which would also stop product sales counting at full price toward thresholds - a change for every store pairing a sale with a spend offer, not only stores giving gifts. Rejected: reading the gift's persisted discount rows, because rules are evaluated before the recalculation writes them, so the answer would lag a recalculation behind. Deferred to separate issues: delivery method item-total rules and the business order minimum still count the gift.
+
+**Consequences:** A gift promotion with a spend threshold now takes its gift back when the paid goods fall below it, which makes the 2026-09-23 limit more visible: a shopper whose own copy was made free loses that copy when the offer lapses. With two gift promotions whose gifts each qualify the other, the one-level judgement can differ from the full one; neither loops. Measuring costs a lookup of the gift promotions whose gifts are in the cart on each rule check; a full cart recalculation went from 1,026 to 1,110 queries on a 23-line cart with three promotions, and from 119 to 121 on a one-line cart without gifts. Caching the measure per recalculation was left out: the baseline is the larger cost, and a cache would have to know every input a rule reads.
+
+**Plans amended:** `6.0-6.1-split-adjustments.md` (the Discount section's `CreateLineItems` note).
+
## 2026-09-24: Store credit is applied rather than chosen, and a gift card follows the total it pays
**Context:** A buyer with a gift card that did not cover the cart was offered Store Credit as the only payment method, and Place Order did nothing (V-3668). Reproduced on `main` against a fresh install, which seeds exactly one payment method, Store Credit: $44.99 cart, card with $10.01 left, amount due $34.98, `payment_methods` `[Store Credit]`, and `POST /carts/:id/payments` answered 422 "Source can't be blank". The gift card was only what put Store Credit in the list: a buyer holding store credit and no gift card failed the same way, because that endpoint builds a payment with no source and a store credit payment needs one. The docs already describe store credit as a balance applied through `POST /carts/:id/store_credits` before choosing how to pay. Testing the combinations turned up four more defects. A gift card's payment never moved with the total: the resize existed as `Order#recalculate_store_credit_payment`, ran from `before_transition to: :payment`, and lost its only caller when the state machine went (6ff55b19f8), so a buyer paid $5.00 by card where $2.99 was owed while the gift card still held $2.01 — and switching to a cheaper delivery left the card paying the old, higher amount. Any change to a store credit payment's amount made the order impossible to place ("Could not find store credit"): `PaymentMethod::StoreCredit#purchase` takes a payment against the eligibility event recorded for its amount, and only creation recorded one. Applying credit, adding an address and applying credit again was enough. The same resize also counted the payment twice against its own credit, so a $30 credit ended up behind a $44.99 payment, the cart showed nothing due, and Place Order failed. `StoreCredits::Apply` spent a gift card's credit as if it were the buyer's own, so the card's balance paid for another cart while its own cart could neither be placed nor have the card removed. And mixing the two was refused in one direction only: store credit applied after a gift card inflated the card's payment, $10.01 of balance ending up behind $24.99 of payments.
diff --git a/docs/user/promotions/promotion-actions.mdx b/docs/user/promotions/promotion-actions.mdx
index 40b6125142..8039f8fed3 100644
--- a/docs/user/promotions/promotion-actions.mdx
+++ b/docs/user/promotions/promotion-actions.mdx
@@ -33,7 +33,7 @@ Each qualifying item will receive a proportional discount based on the calculato
### Create Line Items
-Automatically adds products to the customer’s cart, free of charge, when the promotion applies.
+Automatically adds products to the customer’s cart, free of charge, when the promotion applies. The free product does not count toward spend thresholds or toward the amount a percentage-off discount is taken from, including this promotion's own threshold: with "Spend \$100, get a free tote", the tote is removed once the paid items drop to \$100 or less.
Common uses:
diff --git a/docs/user/promotions/promotion-rules.mdx b/docs/user/promotions/promotion-rules.mdx
index 65705b1de1..7e15cca9b6 100644
--- a/docs/user/promotions/promotion-rules.mdx
+++ b/docs/user/promotions/promotion-rules.mdx
@@ -22,7 +22,7 @@ Below is a list of all rule types currently supported in Spree, along with when
### Item Total
-Applies the promotion only if the order total meets a specific threshold.
+Applies the promotion only if the order total meets a specific threshold. Free gifts added by a promotion do not count toward the total.
Use this when:
diff --git a/spree/core/app/models/concerns/spree/purchase/totals.rb b/spree/core/app/models/concerns/spree/purchase/totals.rb
index 9340d5c7ae..db563c151d 100644
--- a/spree/core/app/models/concerns/spree/purchase/totals.rb
+++ b/spree/core/app/models/concerns/spree/purchase/totals.rb
@@ -10,9 +10,37 @@ module Spree
line_items.sum(:quantity)
end
+ # What promotion calculators take a share of: the line amounts less the
+ # free gifts, so a gift never enlarges a percentage off the order.
+ #
# @return [BigDecimal]
def amount
- line_items.sum(BigDecimal('0'), &:amount)
+ line_items.sum(BigDecimal('0'), &:amount) - gift_amount
+ end
+
+ # The list price of the units gift promotions give away. The gift keeps
+ # its price on its line and is paid for by a discount, so anything
+ # measuring what the shopper spends has to take it out.
+ #
+ # @param promotion [Spree::Promotion, nil] the promotion doing the
+ # measuring; its own gifts are always taken out, since a gift cannot
+ # be what qualifies the promotion giving it away
+ # @param own_gift_only [Boolean] true while deciding whether another
+ # promotion gives its gift, so two gift promotions with spend
+ # thresholds do not each wait on the other
+ # @return [BigDecimal]
+ def gift_amount(promotion: nil, own_gift_only: false)
+ return BigDecimal('0') if line_items.empty?
+
+ excluded_gift_promo_actions = gift_promo_actions(promotion, own_gift_only).select do |action|
+ action.promotion_id == promotion&.id || action.gives_away?(self)
+ end
+ return BigDecimal('0') if excluded_gift_promo_actions.empty?
+
+ line_items.sum(BigDecimal('0')) do |line_item|
+ gifted_quantity = excluded_gift_promo_actions.sum { |action| action.gifted_quantity_of(line_item) }
+ line_item.price * [gifted_quantity, line_item.quantity].min
+ end
end
# Re-sums what the customer has actually paid, and nothing else. A
@@ -78,6 +106,26 @@ module Spree
private
+ # Other promotions' gifts are looked for among the promotions a
+ # recalculation writes discounts for, so a gift leaves the measure
+ # exactly when its discount can be written.
+ def gift_promo_actions(promotion, own_gift_only)
+ own = promotion ? promotion.actions.grep(Spree::Promotion::Actions::CreateLineItems) : []
+ return own if own_gift_only
+
+ discounting_ids = promotion_ids + Spree::Promotion.held_by_saved_coupon_code(self).map(&:id)
+ return own if discounting_ids.empty?
+
+ gifting_cart_variants = Spree::PromotionActionLineItem.
+ where(variant_id: line_items.map(&:variant_id)).
+ select(:promotion_action_id)
+ others = Spree::Promotion::Actions::CreateLineItems.
+ where(promotion_id: discounting_ids, id: gifting_cart_variants).
+ includes(:promotion, :promotion_action_line_items)
+
+ (own + others.to_a).uniq(&:id)
+ end
+
# Completed payments less their refunds, as a scalar subquery so the
# sum and the write are one statement.
#
diff --git a/spree/core/app/models/spree/adjusters/promotion.rb b/spree/core/app/models/spree/adjusters/promotion.rb
index f173d23803..8f9089f147 100644
--- a/spree/core/app/models/spree/adjusters/promotion.rb
+++ b/spree/core/app/models/spree/adjusters/promotion.rb
@@ -65,22 +65,8 @@ module Spree
end
end
- # The owner's PERSISTED coupon code keeps its promotion in candidacy
- # even before it ever applied — the discount activates on the 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.
def coupon_promotions
- return [] unless order.class.respond_to?(:column_names) && order.class.column_names.include?('coupon_code')
-
- code = order.read_attribute(:coupon_code)
- return [] if code.blank?
-
- promotion = order.store.promotions.active.with_coupon_code(code)
- return [] if promotion.nil? || promotion.usage_limit_exceeded?(order)
-
- [promotion]
+ Spree::Promotion.held_by_saved_coupon_code(order)
end
# A coupon promotion that produced rows becomes an applied promotion —
diff --git a/spree/core/app/models/spree/promotion.rb b/spree/core/app/models/spree/promotion.rb
index 58c7402f5f..d6fe3cf364 100644
--- a/spree/core/app/models/spree/promotion.rb
+++ b/spree/core/app/models/spree/promotion.rb
@@ -106,6 +106,27 @@ module Spree
where('spree_promotions.expires_at IS NULL OR spree_promotions.expires_at > ?', Time.current)
end
+ # The promotion a purchase's PERSISTED coupon code names, which keeps it in
+ # candidacy even before it ever applied — the discount activates on the
+ # 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.
+ #
+ # @param purchase [Spree::Cart, Spree::Order]
+ # @return [Array<Spree::Promotion>] empty, or the one promotion
+ def self.held_by_saved_coupon_code(purchase)
+ return [] unless purchase.class.respond_to?(:column_names) && purchase.class.column_names.include?('coupon_code')
+
+ code = purchase.read_attribute(:coupon_code)
+ return [] if code.blank?
+
+ promotion = purchase.store.promotions.active.with_coupon_code(code)
+ return [] if promotion.nil? || promotion.usage_limit_exceeded?(purchase)
+
+ [promotion]
+ end
+
def self.order_activatable?(promotable)
# Carts have no cancellation concept — only placed orders can be canceled.
promotable && !promotable.completed? && !(promotable.is_a?(Spree::Order) && promotable.canceled?)
@@ -278,9 +299,9 @@ module Spree
checkouts_credited(credits)
end
- def line_item_actionable?(order, line_item)
- if eligible? order
- rules = eligible_rules(order)
+ def line_item_actionable?(order, line_item, options = {})
+ if eligible?(order, options)
+ rules = eligible_rules(order, options)
if rules.blank?
true
else
diff --git a/spree/core/app/models/spree/promotion/actions/create_line_items.rb b/spree/core/app/models/spree/promotion/actions/create_line_items.rb
index 1bb261aad2..c551badbc8 100644
--- a/spree/core/app/models/spree/promotion/actions/create_line_items.rb
+++ b/spree/core/app/models/spree/promotion/actions/create_line_items.rb
@@ -104,6 +104,31 @@ module Spree
quantifier.can_supply? quantity
end
+ # Whether the promotion gives its gift on this order, judged with other
+ # promotions' gifts still counting toward its own rules — a single
+ # level, so two gift promotions measuring each other cannot loop.
+ #
+ # @param order [Spree::Order, Spree::Cart]
+ # @return [Boolean]
+ def gives_away?(order)
+ promotion.eligible?(order, own_gift_only: true) && qualifies_beyond_the_gift?(order, own_gift_only: true)
+ end
+
+ # How many units of this line the promotion pays for — never more than
+ # the line holds, so a shopper buying three of a variant gifted once
+ # still pays for two. `quantity` is nullable and written by `upsert_all`,
+ # which skips validation, so a missing or negative one gifts nothing
+ # rather than raising or turning the discount into a surcharge.
+ #
+ # @param line_item [Spree::LineItem]
+ # @return [Integer]
+ def gifted_quantity_of(line_item)
+ gifted = promotion_action_line_items.detect { |item| item.variant_id == line_item.variant_id }
+ return 0 if gifted.nil?
+
+ [[line_item.quantity, gifted.quantity.to_i].min, 0].max
+ end
+
private
# Whether this line holds a variant the promotion gives away.
@@ -117,30 +142,15 @@ module Spree
# to hold a line the rules count with units this action is not already
# covering. A promotion with no rules qualifies on anything, so there is
# nothing for the gift to stand in for.
- def qualifies_beyond_the_gift?(order)
+ def qualifies_beyond_the_gift?(order, options = {})
return true if promotion.promotion_rules.empty?
order.line_items.any? do |line_item|
- promotion.line_item_actionable?(order, line_item) &&
+ promotion.line_item_actionable?(order, line_item, options) &&
gifted_quantity_of(line_item) < line_item.quantity
end
end
- # How many units of this line the promotion pays for — never more than
- # the line holds, so a shopper buying three of a variant gifted once
- # still pays for two. `quantity` is nullable and written by `upsert_all`,
- # which skips validation, so a missing or negative one gifts nothing
- # rather than raising or turning the discount into a surcharge.
- #
- # @param line_item [Spree::LineItem]
- # @return [Integer]
- def gifted_quantity_of(line_item)
- gifted = promotion_action_line_items.detect { |item| item.variant_id == line_item.variant_id }
- return 0 if gifted.nil?
-
- [[line_item.quantity, gifted.quantity.to_i].min, 0].max
- end
-
def add_missing_line_items(order)
added_results = promotion_action_line_items.map do |item|
missing = item.quantity.to_i - order.quantity_of(item.variant)
diff --git a/spree/core/app/models/spree/promotion/rules/item_total.rb b/spree/core/app/models/spree/promotion/rules/item_total.rb
index 9bcd8e7abf..a7415533ad 100644
--- a/spree/core/app/models/spree/promotion/rules/item_total.rb
+++ b/spree/core/app/models/spree/promotion/rules/item_total.rb
@@ -1,5 +1,5 @@
# A rule to apply to an order greater than (or greater than or equal to)
-# a specific amount
+# a specific amount. Free gifts do not count toward it.
module Spree
class Promotion
module Rules
@@ -16,8 +16,8 @@ module Spree
promotable.is_a?(Spree::Order) || promotable.is_a?(Spree::Cart)
end
- def eligible?(order, _options = {})
- item_total = order.item_total
+ def eligible?(order, options = {})
+ item_total = order.item_total - order.gift_amount(promotion: promotion, own_gift_only: options.fetch(:own_gift_only, false))
lower_limit_condition = item_total.send(preferred_operator_min == 'gte' ? :>= : :>, BigDecimal(preferred_amount_min.to_s))
diff --git a/spree/core/spec/models/spree/promotion/actions/create_line_items_spec.rb b/spree/core/spec/models/spree/promotion/actions/create_line_items_spec.rb
index e16068a75c..3c2e7e1d5e 100644
--- a/spree/core/spec/models/spree/promotion/actions/create_line_items_spec.rb
+++ b/spree/core/spec/models/spree/promotion/actions/create_line_items_spec.rb
@@ -202,14 +202,9 @@ describe Spree::Promotion::Actions::CreateLineItems, type: :model do
expect(gift_line_item.discounts.sum(&:amount)).to eq(-15)
end
- # A $20 order is inside a 15..25 range until the $15 gift lands and takes it
- # to $35. The rule is still enforced — the promotion is ineligible and the
- # gift earns no discount — but the promotion joins the order on the strength
- # of the add alone, which is the only thing that lets `revert` reach the
- # gift. This configuration leaves a paid-for gift in the cart; it does so on
- # 5.6 too, and closing it needs a gift to stop counting toward the rule that
- # gave it.
- it 'joins the promotion, unfreed, when the gift takes the order out of range' do
+ # A $20 order is inside a 15..25 range; the $15 gift takes the item total
+ # to $35 but does not count toward the rule that gave it.
+ it 'keeps the gift free when its price would take the order out of range' do
Spree::Promotion::Rules::ItemTotal.create!(
promotion: promotion,
preferred_operator_min: 'gte', preferred_amount_min: 15,
@@ -220,12 +215,131 @@ describe Spree::Promotion::Actions::CreateLineItems, type: :model do
promotion.reload
expect(promotion.activate(order: cart)).to be(true)
- expect(cart.promotions.reload).to include(promotion)
+ Spree.cart_recalculate_totals_workflow.call(cart: cart)
cart.reload
- expect(promotion.eligible?(cart)).to be(false)
- expect(gift_line_item.discounts).to be_empty
+ expect(promotion.eligible?(cart)).to be(true)
+ expect(gift_line_item.discounts.sum(&:amount)).to eq(-15)
expect(cart.item_total).to eq(35)
+ expect(cart.total).to eq(20)
+ end
+ end
+
+ # The gift keeps its price on its line and is paid for by a discount, so
+ # without taking it out a spend threshold or a percentage off would count it.
+ describe 'counting toward what the shopper spends' do
+ let(:cart) { create(:cart) }
+ let(:blender) { create(:variant, price: 20) }
+ let(:gift) { create(:variant, price: 15) }
+ let!(:ten_percent_over_50) do
+ automatic_promotion.tap do |spend_promotion|
+ spend_over(spend_promotion, 50)
+ create(:promotion_action_create_adjustment, promotion: spend_promotion, calculator: build(:flat_percent_item_total_calculator))
+ end
+ end
+
+ def automatic_promotion
+ create(:promotion, kind: :automatic, code: nil, store: cart.store)
+ end
+
+ def spend_over(promotion, amount)
+ Spree::Promotion::Rules::ItemTotal.create!(promotion: promotion, preferred_operator_min: 'gt', preferred_amount_min: amount)
+ end
+
+ def gift_with(promotion, variant = gift)
+ create(:promotion_action_create_line_items, promotion: promotion).
+ promotion_action_line_items.create!(variant: variant, quantity: 1)
+ end
+
+ def gift_promotion_buying(product)
+ automatic_promotion.tap do |gift_promotion|
+ create(:promotion_rule_product, promotion: gift_promotion).products << product
+ gift_with(gift_promotion)
+ end
+ end
+
+ def add(variant, quantity)
+ Spree.cart_add_item_workflow.call(cart: cart, variant: variant, quantity: quantity)
+ cart.reload
+ end
+
+ def gift_line_item
+ cart.line_items.reload.find_by(variant_id: gift.id)
+ end
+
+ def discount_from(promotion)
+ cart.discounts.reload.where(promotion: promotion).sum(:amount)
+ end
+
+ context 'when another promotion gives the gift away' do
+ before { gift_promotion_buying(blender.product) }
+
+ it 'does not let the gift lift the order over a threshold' do
+ add(blender, 2)
+
+ expect(gift_line_item.discounts.sum(&:amount)).to eq(-15)
+ expect(cart.item_total).to eq(55)
+ expect(discount_from(ten_percent_over_50)).to eq(0)
+ expect(cart.total).to eq(40)
+ end
+
+ it 'takes a percentage of the paid goods only' do
+ add(blender, 3)
+
+ expect(discount_from(ten_percent_over_50)).to eq(-6)
+ expect(cart.total).to eq(54)
+ end
+ end
+
+ it 'counts a copy of the gift the shopper pays for' do
+ gift_promotion_buying(create(:product))
+ add(blender, 2)
+ add(gift, 1)
+
+ expect(discount_from(ten_percent_over_50)).to eq(-5.5)
+ expect(cart.total).to eq(49.5)
+ end
+
+ it 'counts the gift until its promotion applies to the cart and discounts it' do
+ add(blender, 2)
+ add(gift, 1)
+ gift_promotion = gift_promotion_buying(blender.product)
+
+ Spree.cart_recalculate_totals_workflow.call(cart: cart)
+
+ expect(discount_from(gift_promotion)).to eq(0)
+ expect(discount_from(ten_percent_over_50)).to eq(-5.5)
+ end
+
+ context 'when the gift promotion has its own threshold' do
+ before do
+ gift_promotion = automatic_promotion
+ spend_over(gift_promotion, 50)
+ gift_with(gift_promotion)
+ end
+
+ it 'takes the gift back once the paid goods fall below it' do
+ add(blender, 3)
+ expect(gift_line_item.discounts.sum(&:amount)).to eq(-15)
+
+ Spree.cart_upsert_items_workflow.call(cart: cart, items: [{ variant_id: blender.id, quantity: 2 }])
+
+ expect(gift_line_item).to be_nil
+ expect(cart.reload.total).to eq(40)
+ end
+
+ it 'settles beside a second gift promotion with a threshold of its own' do
+ second_gift = create(:variant, price: 10)
+ second_promotion = automatic_promotion
+ spend_over(second_promotion, 50)
+ gift_with(second_promotion, second_gift)
+
+ add(blender, 3)
+
+ expect(cart.line_items.map(&:variant_id)).to contain_exactly(blender.id, gift.id, second_gift.id)
+ expect(discount_from(ten_percent_over_50)).to eq(-6)
+ expect(cart.total).to eq(54)
+ end
end
end