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: the free-gift promotion action charged for the gift (#14712)
Łukasz Adamczyk340a5448f991
diff --git a/docs/developer/core-concepts/promotions.mdx b/docs/developer/core-concepts/promotions.mdxindex 5cc4639db7..2a10ae6690 100644--- a/docs/developer/core-concepts/promotions.mdx+++ b/docs/developer/core-concepts/promotions.mdx@@ -137,7 +137,9 @@ Writes a discount on each fulfillment covering its delivery cost. The row is kep### Free items (`CreateLineItems`)-Adds specified products to the cart when the promotion is eligible, checking stock first. Items are not removed automatically if eligibility is lost — customers remove them manually.+Adds specified products to the cart when the promotion is eligible, checking stock first, and discounts them to zero. A customer who already has the gift in their cart gets theirs free rather than a duplicate; any further copies they bought stay paid for. The gift is taken back when the promotion stops applying.++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.**Use case:** "Free gift with purchase", "Spend $100 get a free sample".diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdxindex 85a26189d4..2033827419 100644--- a/docs/developer/upgrades/5.6-to-6.0.mdx+++ b/docs/developer/upgrades/5.6-to-6.0.mdx@@ -391,6 +391,16 @@ A handler receives the workflow (so it can read `order`, `items`, `created_by`,- **Customers are emailed their download links** when the order is placed, from the new `Spree::DigitalAssetMailer` in the optional `spree_emails` gem. Hosts that already send their own download email should either suppress it (`send_consumer_transactional_emails`) or drop their own. The dashboard's order page can re-send it.- **Digital assets are managed through the Admin API and dashboard**, and signed-in customers can list everything they have bought at `GET /api/v3/store/customers/me/digital_links`.+## Free-gift promotions price their own gift++The `Create line items` promotion action now discounts the items it adds down to zero. It used to add them at their full price and leave the discounting to you.++<Warning>+ **Delete the second action if you paired one with it.** The old guidance was to add a whole-order discount set to the gift's price to pay for the gift. That discount still applies, so a promotion configured the old way now discounts twice — the gift is free *and* the order discount comes off. Open each promotion using `Create line items`, and remove the accompanying `Create whole-order adjustment` that exists only to cancel out the gift.+</Warning>++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.+## Dependency injection changes6.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.mdindex bcf5777597..798aa72433 100644--- a/docs/plans/6.0-6.1-split-adjustments.md+++ b/docs/plans/6.0-6.1-split-adjustments.md@@ -195,6 +195,8 @@ 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?`.+### Fee (extensible, taxable)```rubydiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 557dea2d28..83cf13d9b6 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,15 @@+## 2026-09-23: The free-gift action prices its own gift, and covers the copy the shopper already has++**Context:** The `Create line items` action added its variant at full price and wrote no discount, so the promotion raised the bill: a cart of 2 x $89.99 became $269.97 when an automatic gift promotion applied, with no line saying why, and the shopper could not delete the gift because every recalculation put it back (V-3666). The action was the only one describing itself in the docs without saying how the money worked - "Free items", "free items in the cart", "Free gift with purchase" - while `discount_scope` answered nil, which is what excluded it from `Spree::Adjusters::Promotion`. The documented workaround, pairing it with an order discount set to the gift's price, was tested and fails three ways: the order-level amount prorates across every line, so the gift reads as an $8.57 purchase and the $20 item beside it as $11.43; the discount still pays out when the gift is out of stock, because `Promotion#activate` maps over actions independently ($20 cart, $15 off, no gift); and the compensation competes for the order group under 6.0 winner-only, so a larger promotion deletes it and the bill goes back up ($2.00 to $17.00 on entering a free-gift coupon).++**Decision:** The action prices what it adds. `CreateLineItems#discount_scope` is `:line_item` and `#compute_amount` returns `-price * gifted_quantity`, where gifted quantity is the configured quantity capped at what the line holds - so a shopper buying three of a variant gifted once still pays for two. The gift's discount is not narrowed by the promotion's rules: `PromotionAction#applies_to_line_item?` is a new seam defaulting to `promotion.line_item_actionable?`, which `CreateLineItems` overrides with "is this one of my gift variants". Without it the rules decide the gift line, and the ordinary shape of the offer - buy a coffee maker, get a tote - has a gift the rules never name. A shopper who already holds the gift variant gets theirs free rather than a duplicate, which also settles the reported half where `perform` returned false, `activate` therefore returned false, and the promotion refused to attach at all while `eligible?` was true.++Rejected: a configurable gift price, which is what the issue's "or to the configured amount" asks for. It needs a column on `spree_promotion_action_line_items` and an editor field, and free is what every surface already promises. Rejected: leaving the price alone and rewriting the descriptions to say the action charges, the issue's other option - it would have to retract "free items in the cart" from the overview sentence defining what promotions do. Rejected: keeping the gift discount out of the winner-only competition entirely; it wins on its own line anyway, being the whole of it, and a bigger line-level promotion displacing it only ever makes the shopper pay less.++**Consequences:** `revert` now runs only when the promotion is actually joined to the order. It was deleting the gift variant from the cart of any shopper who had bought one themselves and did not qualify, on every recalculation, because the handler deactivates every promotion in scope whether or not it ever applied. What it still cannot do is tell a unit it gave from a unit the shopper bought, so a shopper whose own copy was made free loses that copy when the offer lapses; closing that needs the gifted quantity recorded per line, which no table holds. Installs that followed the old documented recipe now discount twice - the gift is free and the compensating order discount still fires, $20 of goods for $5 in the tested case - so the upgrade note is to delete the compensating action; the docs that taught it are corrected here. The gift still reappears when a shopper deletes it under an automatic promotion, now at zero, so it is no longer a charge but still an item they did not ask for. `types_for_discount_scope(:line_item)` gains the action, which had been listing `CreateItemAdjustments` twice.++**Plans amended:** `6.0-6.1-split-adjustments.md` (the Discount section's per-action notes).+## 2026-09-22: Store credit names the order it puts right, so payment status counts both ledgers**Context:** An order refunded to store credit went on reading `paid`. Reproduced on `main`: order R1016, total $99.99, one $89.99 line returned and refunded as credit — the return reported `refunded_total` $89.99 and `refundable_total` $0.00 while the order reported `payment_status: paid` and nothing given back. A claim behaves the same, and lands there by default, since the claim resolve dialog and `ClaimActions#resolve` both default to `store_credit` where the return side defaults to `original_payment` (V-3660). The cause was a decision applied in one place and not the other: the 2026-08-11 ruling that store credit is its own ledger and never writes a `Spree::Refund` row taught `Return#refunded_total` to sum both, but `Orders::UpdateStatuses#money_for` still counted refund rows alone. V-3561 was closed on the strength of the original-payment half working.diff --git a/docs/user/promotions/create-a-promotion.mdx b/docs/user/promotions/create-a-promotion.mdxindex 76488e05c1..6e6d619641 100644--- a/docs/user/promotions/create-a-promotion.mdx+++ b/docs/user/promotions/create-a-promotion.mdx@@ -98,7 +98,7 @@ Available actions include:- **Create whole-order adjustment** - Applies a discount to the entire order.- **Create per-line-item adjustment** - Applies discounts to individual line items.-- **Create line items** - Automatically adds products (e.g. gifts) to the cart.+- **Create line items** - Automatically adds products (e.g. gifts) to the cart, free of charge.- **Free shipping** - Makes all shipments for the order free.Each action supports one or more calculators (e.g. flat rate, percentage, tiered discounts). These are covered in detail in [<u>Promotion Actions</u>](https://spreecommerce.org/docs/user/promotions/promotion-actions).diff --git a/docs/user/promotions/promotion-actions.mdx b/docs/user/promotions/promotion-actions.mdxindex c0eaeea566..40b6125142 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 when the promotion applies.+Automatically adds products to the customer’s cart, free of charge, when the promotion applies.Common uses:@@ -45,7 +45,8 @@ You’ll be able to:- Select the variant(s) to add- Set the quantity-- Combine with other actions to set price rules (e.g., set to free or discounted)++The gift costs the customer nothing on its own, so do not add a second action to pay for it — an order discount set to the gift price would discount it a second time. If a customer already has the gift in their cart, theirs becomes free instead of a duplicate being added.### Free Shipping@@ -86,5 +87,5 @@ You'll choose a calculator when you add the action. The fields shown will depend| :---------------------------------- | :---------------------------------------- | :------------------------------------------ || \$10 off entire order | Whole-order adjustment | Flat Rate || 20% off selected products | Per-line-item adjustment | Flat Percent |-| Add a free tote bag on orders \$50+ | Create line items, Whole-order adjustment | Flat Rate (set to price of added line item) |+| Add a free tote bag on orders \$50+ | Create line items | – || Free shipping on all orders | Free shipping | – |diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.jsonindex 1feca8451b..8da821f4e2 100644--- a/packages/dashboard-core/src/locales/ar.json+++ b/packages/dashboard-core/src/locales/ar.json@@ -1917,7 +1917,7 @@},"create_line_items": {"name": "إنشاء عناصر سطرية",- "description": "تعبئة سلة التسوق بالكمية المحددة من المتغير"+ "description": "يضيف الكمية المحددة من المتغير إلى السلة مجانًا"},"free_shipping": {"name": "الشحن مجانًا",diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.jsonindex 08eef12900..87ef425493 100644--- a/packages/dashboard-core/src/locales/de.json+++ b/packages/dashboard-core/src/locales/de.json@@ -1912,7 +1912,7 @@},"create_line_items": {"name": "Bestellpositionen erstellen",- "description": "Fügt dem Warenkorb die angegebene Menge der Variante hinzu"+ "description": "Fügt dem Warenkorb die angegebene Menge der Variante kostenlos hinzu"},"free_shipping": {"name": "Kostenloser Versand",diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.jsonindex 3f59a18086..58505ac1c8 100644--- a/packages/dashboard-core/src/locales/en.json+++ b/packages/dashboard-core/src/locales/en.json@@ -1914,7 +1914,7 @@},"create_line_items": {"name": "Create line items",- "description": "Populates the cart with the specified quantity of variant"+ "description": "Adds the specified quantity of a variant to the cart free of charge"},"free_shipping": {"name": "Free shipping",diff --git a/packages/dashboard-core/src/locales/es.json b/packages/dashboard-core/src/locales/es.jsonindex 6918d14b11..8f5d54d44a 100644--- a/packages/dashboard-core/src/locales/es.json+++ b/packages/dashboard-core/src/locales/es.json@@ -1293,7 +1293,7 @@},"create_line_items": {"name": "Crear líneas de pedido",- "description": "Completa el carrito con la cantidad especificada de la variante"+ "description": "Agrega al carrito la cantidad especificada de la variante de forma gratuita"},"free_shipping": {"name": "Envío gratis",diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.jsonindex 73032ac81b..3d3466964d 100644--- a/packages/dashboard-core/src/locales/fr.json+++ b/packages/dashboard-core/src/locales/fr.json@@ -1912,7 +1912,7 @@},"create_line_items": {"name": "Créer des lignes d'article",- "description": "Ajoute au panier la quantité spécifiée de la variante"+ "description": "Ajoute gratuitement au panier la quantité spécifiée de la variante"},"free_shipping": {"name": "Livraison gratuite",diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.jsonindex 67b917c6d8..14077dae4f 100644--- a/packages/dashboard-core/src/locales/pl.json+++ b/packages/dashboard-core/src/locales/pl.json@@ -1941,7 +1941,7 @@},"create_line_items": {"name": "Utwórz pozycje zamówienia",- "description": "Dodaje do koszyka określoną ilość wariantu"+ "description": "Dodaje do koszyka określoną ilość wariantu za darmo"},"free_shipping": {"name": "Darmowa wysyłka",diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.jsonindex fc12d9b239..01e2338177 100644--- a/packages/dashboard-core/src/locales/zh-CN.json+++ b/packages/dashboard-core/src/locales/zh-CN.json@@ -1911,7 +1911,7 @@},"create_line_items": {"name": "创建订单项",- "description": "向购物车填充指定数量的变体"+ "description": "将指定数量的变体免费加入购物车"},"free_shipping": {"name": "免运费",diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex c6746598df..8fbf9a0a91 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -571,7 +571,7 @@"settings_label": "إعدادات الآلة الحاسبة"},"create_line_items_action_editor": {- "description": "عند تأهل العرض الترويجي، تُضاف هذه العناصر إلى السلة.",+ "description": "عند تأهل العرض الترويجي، تُضاف هذه العناصر إلى السلة مجانًا.","empty": "لا توجد متغيرات بعد. ابحث أدناه لإضافة واحد.","search_placeholder": "ابحث عن المتغيرات بالاسم أو SKU…","variant_label": "إضافة متغير"diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex d70333b51f..652da6fa52 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -564,7 +564,7 @@"settings_label": "Kalkulator-Einstellungen"},"create_line_items_action_editor": {- "description": "Wenn die Promotion greift, werden diese Artikel dem Warenkorb hinzugefügt.",+ "description": "Wenn die Promotion greift, werden diese Artikel dem Warenkorb kostenlos hinzugefügt.","empty": "Noch keine Varianten. Suchen Sie unten, um eine hinzuzufügen.","search_placeholder": "Varianten nach Name oder SKU suchen…","variant_label": "Variante hinzufügen"diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 53181d2ff3..3f23b84cf9 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -564,7 +564,7 @@"settings_label": "Calculator settings"},"create_line_items_action_editor": {- "description": "When the promotion qualifies, these items are added to the cart.",+ "description": "When the promotion qualifies, these items are added to the cart free of charge.","empty": "No variants yet. Search below to add one.","search_placeholder": "Search variants by name or SKU…","variant_label": "Add variant"diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex e635922f58..df04c2d871 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -5389,7 +5389,7 @@"settings_label": "Configuración de la calculadora"},"create_line_items_action_editor": {- "description": "Cuando la promoción califica, estos artículos se agregan al carrito.",+ "description": "Cuando la promoción califica, estos artículos se agregan al carrito de forma gratuita.","empty": "Todavía no hay variantes. Buscá abajo para agregar una.","search_placeholder": "Buscar variantes por nombre o SKU…","variant_label": "Agregar variante"diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 18c1b932fe..f13adfe1a1 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -564,7 +564,7 @@"settings_label": "Paramètres du calculateur"},"create_line_items_action_editor": {- "description": "Lorsque la promotion est éligible, ces articles sont ajoutés au panier.",+ "description": "Lorsque la promotion est éligible, ces articles sont ajoutés gratuitement au panier.","empty": "Aucune variante pour l'instant. Recherchez ci-dessous pour en ajouter une.","search_placeholder": "Rechercher des variantes par nom ou SKU…","variant_label": "Ajouter une variante"diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 714e8bf19f..86067ba555 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -574,7 +574,7 @@"settings_label": "Ustawienia kalkulatora"},"create_line_items_action_editor": {- "description": "Gdy promocja kwalifikuje się, te pozycje są dodawane do koszyka.",+ "description": "Gdy promocja kwalifikuje się, te pozycje są dodawane do koszyka za darmo.","empty": "Brak wariantów. Wyszukaj poniżej, aby dodać.","search_placeholder": "Szukaj wariantów po nazwie lub SKU…","variant_label": "Dodaj wariant"diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 926e43ae85..0ce0f0e667 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -562,7 +562,7 @@"settings_label": "计算器设置"},"create_line_items_action_editor": {- "description": "当促销符合条件时,这些商品会加入购物车。",+ "description": "当促销符合条件时,这些商品会免费加入购物车。","empty": "尚无变体。请在下方搜索以添加。","search_placeholder": "按名称或 SKU 搜索变体…","variant_label": "添加变体"diff --git a/spree/core/app/models/spree/adjusters/promotion.rb b/spree/core/app/models/spree/adjusters/promotion.rbindex 24ab3efb80..f173d23803 100644--- a/spree/core/app/models/spree/adjusters/promotion.rb+++ b/spree/core/app/models/spree/adjusters/promotion.rb@@ -113,7 +113,7 @@ module Spreedef line_item_candidates(line_item)@line_item_candidates ||= {}@line_item_candidates[line_item.id] ||= discount_actions(:line_item).filter_map do |action|- next unless action.promotion.line_item_actionable?(order, line_item)+ next unless action.applies_to_line_item?(order, line_item)amount = action.compute_amount(line_item)next if amount.zero?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.rbindex 03532b4cd0..1bb261aad2 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@@ -19,7 +19,33 @@ module Spreedelegate :eligible?, to: :promotion- # Adds a line item to the Order if the promotion is eligible+ # @return [Symbol]+ def discount_scope+ :line_item+ end++ # The gift is rarely the product the rules name ("buy a coffee maker,+ # get a free tote"), so the rules decide whether the promotion applies+ # and this action decides which lines it pays for.+ #+ # @param order [Spree::Order, Spree::Cart]+ # @param line_item [Spree::LineItem]+ # @return [Boolean]+ def applies_to_line_item?(order, line_item)+ gifted_item?(line_item) && qualifies_beyond_the_gift?(order)+ end++ # Covers the gifted units of the line at their own price, leaving any+ # further units of the same variant the shopper bought themselves to be+ # paid for.+ #+ # @param line_item [Spree::LineItem]+ # @return [BigDecimal] never positive+ def compute_amount(line_item)+ line_item.price * gifted_quantity_of(line_item) * -1+ end++ # Tops the order up to the promised quantity and discounts it.## This doesn't play right with Add to Cart events because at the moment# the item was added to cart the promo may not be eligible. However it@@ -32,46 +58,26 @@ module Spree# - Customer increases item quantity to 5 (order total goes to $50)# - Now the order is eligible for the promo and the action should perform#- # Another complication is when the same line item created by the promo- # is also added to cart on a separate action.- #- # e.g.- # - Promo adds 1 item A to cart if order total greater then $30- # - Customer add 2 items B to cart, current order total is $40- # - This action performs adding item A to cart since order is eligible- # - Customer changes his mind and updates item B quantity to 1- # - At this point order is no longer eligible and one might expect- # that item A should be removed- #- # It doesn't remove items from the order here because there's no way- # it can know whether that item was added via this promo action or if- # it was manually populated somewhere else. In that case the item- # needs to be manually removed from the order by the customer+ # A shopper who already has the gift variant is given theirs free rather+ # than a duplicate, so the promotion still applies when it has nothing+ # to add.def perform(options = {})order = options[:order]return unless eligible? order+ return unless qualifies_beyond_the_gift?(order)- action_taken = false- promotion_action_line_items.each do |item|- current_quantity = order.quantity_of(item.variant)- next unless current_quantity < item.quantity && item_available?(item)+ added = add_missing_line_items(order)- add_service = order.is_a?(Spree::Cart) ? Spree.cart_add_item_workflow : Spree.order_add_item_service- line_item = add_service.call(**{ (order.is_a?(Spree::Cart) ? :cart : :order) => order },- variant: item.variant,- quantity: item.quantity - current_quantity).value- action_taken = true if line_item.try(:valid?)- end- action_taken+ apply_via_adjuster(options) || addedend# Called by promotion handler when a promotion is removed# This will find any line item matching the ones defined in the PromotionAction# and remove the same quantity as was added by the PromotionAction.- # Should help to prevent some of cases listed above the #perform methoddef revert(options = {})order = options[:order]return if eligible?(order)+ return unless order.promotions.include?(promotion)action_taken = falsepromotion_action_line_items.each do |item|@@ -89,13 +95,69 @@ module Spreeend# Checks that there's enough stock to add the line item to the order- def item_available?(item)+ #+ # @param item [Spree::PromotionActionLineItem]+ # @param quantity [Integer] units wanted, defaulting to the whole gift+ # @return [Boolean]+ def item_available?(item, quantity = item.quantity)quantifier = Spree::Stock::Quantifier.new(item.variant)- quantifier.can_supply? item.quantity+ quantifier.can_supply? quantityendprivate+ # Whether this line holds a variant the promotion gives away.+ def gifted_item?(line_item)+ gifted_quantity_of(line_item).positive?+ end++ # A gift cannot be the thing that qualifies the order for the promotion+ # giving it away: a rule naming the gift's own product would otherwise+ # hand the item over to anyone who put it in their cart. The order has+ # 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)+ return true if promotion.promotion_rules.empty?++ order.line_items.any? do |line_item|+ promotion.line_item_actionable?(order, line_item) &&+ 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)+ next false unless missing.positive? && item_available?(item, missing)++ add_service = order.is_a?(Spree::Cart) ? Spree.cart_add_item_workflow : Spree.order_add_item_service+ result = add_service.call(**{ (order.is_a?(Spree::Cart) ? :cart : :order) => order },+ variant: item.variant,+ quantity: missing)+ result.success?+ end++ order.line_items.reload if added_results.any?++ added_results.any?+ end+def promotion_variants_scopepromotion.store.variantsenddiff --git a/spree/core/app/models/spree/promotion_action.rb b/spree/core/app/models/spree/promotion_action.rbindex 631b437816..6708cf20bb 100644--- a/spree/core/app/models/spree/promotion_action.rb+++ b/spree/core/app/models/spree/promotion_action.rb@@ -37,6 +37,17 @@ module Spreefalseend+ # Whether this action's line-level discount may land on +line_item+.+ # Promotion rules narrow it by default; an action that creates its own+ # lines answers for itself.+ #+ # @param order [Spree::Order, Spree::Cart]+ # @param line_item [Spree::LineItem]+ # @return [Boolean]+ def applies_to_line_item?(order, line_item)+ promotion.line_item_actionable?(order, line_item)+ end+# Returns true if the promotion action is a free shipping action## @return [Boolean]@@ -53,7 +64,7 @@ module Spreedef self.types_for_discount_scope(scope)case scopewhen :line_item- %w[Spree::Promotion::Actions::CreateItemAdjustments Spree::Promotion::Actions::CreateItemAdjustments]+ %w[Spree::Promotion::Actions::CreateItemAdjustments Spree::Promotion::Actions::CreateLineItems]when :fulfillment%w[Spree::Promotion::Actions::FreeShipping Spree::Promotion::Actions::FreeShipping]when :orderdiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 63c5499415..91350d43e5 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1577,7 +1577,7 @@ en:description: Creates a promotion credit adjustment on a line itemname: Create per-line-item adjustmentcreate_line_items:- description: Populates the cart with the specified quantity of variant+ description: Adds the specified quantity of a variant to the cart free of chargename: Create line itemsfree_shipping:description: Makes all shipments for the order freediff --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.rbindex e2fa1fbe2b..e16068a75c 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@@ -78,12 +78,155 @@ describe Spree::Promotion::Actions::CreateLineItems, type: :model doendit 'takes the gift back when the promotion stops applying' do- action.perform(order: cart)- allow(promotion).to receive(:eligible?).and_return(false)+ # Through `activate` rather than `perform`, because it is `activate` that+ # joins the promotion to the cart — which is what marks the gift as ours.+ promotion.activate(order: cart)+ # Genuinely ineligible rather than stubbed: removing the gift recalculates+ # the cart, and the handler reloads the promotion from the database.+ create(:promotion_rule_product, promotion: promotion).products << create(:variant).product+ promotion.reloadexpect(action.revert(order: cart)).to be(true)expect(cart.line_items.reload.find_by(variant_id: mug.id)).to be_nilend++ it 'leaves the variant alone on a cart the promotion never applied to' do+ Spree.cart_add_item_workflow.call(cart: cart, variant: mug, quantity: 2)+ allow(promotion).to receive(:eligible?).and_return(false)++ expect(action.revert(order: cart)).to be_nil+ expect(cart.line_items.reload.find_by(variant_id: mug.id).quantity).to eq(2)+ end+ end++ describe 'pricing the gift' do+ let(:cart) { create(:cart) }+ let(:gift) { create(:variant, price: 15) }++ before { action.promotion_action_line_items.create!(variant: gift, quantity: 1) }++ def gift_line_item+ cart.line_items.reload.find_by(variant_id: gift.id)+ end++ it 'discounts the gift it adds down to nothing' do+ promotion.activate(order: cart)+ Spree.cart_recalculate_totals_workflow.call(cart: cart)++ expect(gift_line_item.quantity).to eq(1)+ expect(gift_line_item.discounts.sum(&:amount)).to eq(-15)++ cart.reload+ expect(cart.item_total).to eq(15)+ expect(cart.discount_total).to eq(-15)+ expect(cart.total).to eq(0)+ end++ it 'makes only Y free on a "buy X, get Y free" promotion' do+ qualifying = create(:variant, price: 20)+ create(:promotion_rule_product, promotion: promotion).products << qualifying.product+ Spree.cart_add_item_workflow.call(cart: cart, variant: qualifying, quantity: 1)++ promotion.activate(order: cart)+ Spree.cart_recalculate_totals_workflow.call(cart: cart)++ expect(gift_line_item.quantity).to eq(1)+ expect(gift_line_item.discounts.sum(&:amount)).to eq(-15)+ expect(cart.line_items.reload.find_by(variant_id: qualifying.id).discounts).to be_empty++ cart.reload+ expect(cart.item_total).to eq(35)+ expect(cart.discount_total).to eq(-15)+ expect(cart.total).to eq(20)+ end++ context 'when the rules name the gift\'s own product' do+ before { create(:promotion_rule_product, promotion: promotion).products << gift.product }++ it 'refuses the gift when the only qualifying line is the gift itself' do+ Spree.cart_add_item_workflow.call(cart: cart, variant: gift, quantity: 1)+ promotion.reload++ expect(promotion.activate(order: cart)).to be(false)+ expect(gift_line_item.discounts).to be_empty+ expect(cart.reload.total).to eq(15)+ end++ # The gift stops being free the moment it is the only thing qualifying,+ # and is not re-added, so the shopper can take it out themselves.+ it 'stops paying for the gift when the qualifying line goes' do+ qualifying = create(:variant, price: 20)+ promotion.promotion_rules.first.products << qualifying.product+ Spree.cart_add_item_workflow.call(cart: cart, variant: qualifying, quantity: 1)+ promotion.reload+ promotion.activate(order: cart)+ expect(gift_line_item.discounts.sum(&:amount)).to eq(-15)++ Spree.cart_remove_item_service.call(cart: cart, variant: qualifying, quantity: 1)++ expect(gift_line_item.discounts).to be_empty+ expect(cart.reload.total).to eq(15)+ end++ it 'gifts one once the shopper holds more than the gift covers' do+ Spree.cart_add_item_workflow.call(cart: cart, variant: gift, quantity: 3)+ promotion.reload++ promotion.activate(order: cart)+ Spree.cart_recalculate_totals_workflow.call(cart: cart)++ expect(gift_line_item.quantity).to eq(3)+ expect(gift_line_item.discounts.sum(&:amount)).to eq(-15)++ cart.reload+ expect(cart.item_total).to eq(45)+ expect(cart.discount_total).to eq(-15)+ expect(cart.total).to eq(30)+ end+ end++ it "discounts the shopper's own copy instead of adding a second one" do+ Spree.cart_add_item_workflow.call(cart: cart, variant: gift, quantity: 1)++ expect(promotion.activate(order: cart)).to be(true)+ expect(gift_line_item.quantity).to eq(1)+ expect(gift_line_item.discounts.sum(&:amount)).to eq(-15)+ end++ it 'leaves units beyond the gifted quantity paid for' do+ Spree.cart_add_item_workflow.call(cart: cart, variant: gift, quantity: 3)++ promotion.activate(order: cart)++ expect(gift_line_item.quantity).to eq(3)+ 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+ Spree::Promotion::Rules::ItemTotal.create!(+ promotion: promotion,+ preferred_operator_min: 'gte', preferred_amount_min: 15,+ preferred_operator_max: 'lte', preferred_amount_max: 25+ )+ qualifying = create(:variant, price: 20)+ Spree.cart_add_item_workflow.call(cart: cart, variant: qualifying, quantity: 1)+ promotion.reload++ expect(promotion.activate(order: cart)).to be(true)+ expect(cart.promotions.reload).to include(promotion)++ cart.reload+ expect(promotion.eligible?(cart)).to be(false)+ expect(gift_line_item.discounts).to be_empty+ expect(cart.item_total).to eq(35)+ endenddescribe '#item_available?' do