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: Deleting a promotion applied to open carts no longer breaks them (#15056)
Damian Legawiec12e1cbdc234c
diff --git a/spree/core/app/models/spree/order_promotion.rb b/spree/core/app/models/spree/order_promotion.rbindex 1f6bf17168..4058c38271 100644--- a/spree/core/app/models/spree/order_promotion.rb+++ b/spree/core/app/models/spree/order_promotion.rb@@ -8,7 +8,7 @@ module Spreebelongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :order_promotionsbelongs_to :promotion, class_name: 'Spree::Promotion'- delegate :name, :description, :code, to: :promotion+ delegate :name, :description, :code, to: :promotion, allow_nil: truedelegate :currency, to: :ownervalidates :order, uniqueness: { scope: :promotion }, allow_nil: true@@ -35,6 +35,8 @@ module Spreeenddef amount+ return BigDecimal(0) if promotion.nil?+owner.discounts.promotion.where(promotion_action_id: promotion.actions.ids).sum(:amount)enddiff --git a/spree/core/app/models/spree/promotion.rb b/spree/core/app/models/spree/promotion.rbindex f886904bf4..cab7593833 100644--- a/spree/core/app/models/spree/promotion.rb+++ b/spree/core/app/models/spree/promotion.rb@@ -51,7 +51,8 @@ module Spreebefore_validation :set_starts_at_to_current_time, if: -> { starts_at.blank? }after_commit :generate_coupon_codes, if: -> { multi_codes? }, on: [:create, :update]after_commit :remove_coupons, on: :update- before_destroy :not_used?+ before_destroy :detach_from_open_carts, prepend: true+ before_destroy :not_used?, prepend: true## Validations@@ -376,6 +377,14 @@ module Spreeflush_pending_typed_association(:promotion_actions)end+ # Runs before the promotion's actions are destroyed, since the carts'+ # discounts are tied back to the promotion through them.+ def detach_from_open_carts+ Spree::Cart.where(id: order_promotions.where.not(cart_id: nil).select(:cart_id)).find_each do |cart|+ Spree::Promotions::DetachFromOwner.call(owner: cart, promotion: self, clear_coupon_code: true)+ end+ end+def not_used?return true if orders.empty?diff --git a/spree/core/app/models/spree/promotion_handler/cart.rb b/spree/core/app/models/spree/promotion_handler/cart.rbindex 9efdc4cdb8..d0b9652ae8 100644--- a/spree/core/app/models/spree/promotion_handler/cart.rb+++ b/spree/core/app/models/spree/promotion_handler/cart.rb@@ -16,14 +16,20 @@ module Spreeattr_reader :line_item, :order, :storeattr_accessor :error, :success- def initialize(order, line_item = nil)+ # @param order [Spree::Cart, Spree::Order]+ # @param line_item [Spree::LineItem, nil]+ # @param excluded_promotion_ids [Array<String, Integer>] promotions to leave alone, e.g. one that is being removed+ def initialize(order, line_item = nil, excluded_promotion_ids: [])@order = order@line_item = line_item@store = order.store+ @excluded_promotion_ids = Array(excluded_promotion_ids).map(&:to_s)enddef activatepromotions.each do |promotion|+ next if @excluded_promotion_ids.include?(promotion.id.to_s)+if (line_item && promotion.eligible?(line_item)) || promotion.eligible?(order)promotion.activate(line_item: line_item, order: order)elsediff --git a/spree/core/app/models/spree/promotion_handler/coupon.rb b/spree/core/app/models/spree/promotion_handler/coupon.rbindex 4f4e3ea5cc..d547501207 100644--- a/spree/core/app/models/spree/promotion_handler/coupon.rb+++ b/spree/core/app/models/spree/promotion_handler/coupon.rb@@ -166,35 +166,7 @@ module Spreeenddef 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-- def remove_promotion_line_items(promotion)- create_line_item_actions_ids = promotion.actions.- where(type: %w[Spree::Promotion::Actions::CreateLineItems Spree::Promotion::Actions::CreateLineItems]).pluck(:id)-- Spree::PromotionActionLineItem.where(promotion_action: create_line_item_actions_ids).find_each do |item|- line_item = order.find_line_item_by_variant(item.variant)- next if line_item.blank?-- remove_service = order.is_a?(Spree::Cart) ? Spree.cart_remove_item_service : Spree.order_remove_item_service- remove_service.call(**{ (order.is_a?(Spree::Cart) ? :cart : :order) => order }, variant: item.variant, quantity: item.quantity)- end+ Spree::Promotions::DetachFromOwner.call(owner: order, promotion: promotion)enddef handle_present_promotiondiff --git a/spree/core/app/services/spree/promotions/detach_from_owner.rb b/spree/core/app/services/spree/promotions/detach_from_owner.rbnew file mode 100644index 0000000000..45c9aae227--- /dev/null+++ b/spree/core/app/services/spree/promotions/detach_from_owner.rb@@ -0,0 +1,72 @@+module Spree+ module Promotions+ # Removes a promotion from a cart or an order the way a shopper removing the+ # code does: the order promotion, held coupon code, discounts and items+ # the promotion added are removed, then totals are recalculated.+ #+ # @example Removing a promotion from a cart+ # Spree::Promotions::DetachFromOwner.call(owner: cart, promotion: promotion)+ class DetachFromOwner+ prepend Spree::ServiceModule::Base++ # Action types whose line items are removed along with the promotion.+ CREATE_LINE_ITEMS_ACTION_TYPES = %w[Spree::Promotion::Actions::CreateLineItems].freeze++ # @param owner [Spree::Cart, Spree::Order] the cart or order holding the promotion+ # @param promotion [Spree::Promotion] the promotion to remove+ # @param clear_coupon_code [Boolean] also clear the code the shopper entered on the+ # owner, so recalculating does not apply the promotion again. Leave it off when the+ # shopper should be told the code was lost.+ # @return [Spree::ServiceModule::Result] success, holding the owner; a failure when the+ # owner is already completed, since placed orders are never changed this way+ def call(owner:, promotion:, clear_coupon_code: false)+ return failure(owner, 'Cannot remove a promotion from a completed order') if owner.completed?++ held_code = promotion.coupon_codes.held_by(owner).first if promotion.multi_codes?+ clear_entered_coupon_code(owner, held_code&.code || promotion.code) if clear_coupon_code++ # The order promotion has to go before line items are removed+ owner.promotions.delete(promotion)++ if held_code+ held_code.remove_from_order+ else+ promotion.touch+ end++ owner.discounts.where(promotion_action_id: promotion.actions.ids).destroy_all+ remove_promotion_line_items(owner, promotion)+ owner.recalculate_totals!++ success(owner)+ end++ private++ # Carts keep the entered code, and recalculation would apply it again.+ # Callers that let the shopper be told the code went keep it.+ def clear_entered_coupon_code(owner, code)+ return if code.blank? || !owner.has_attribute?(:coupon_code)+ return unless owner.read_attribute(:coupon_code).to_s.casecmp?(code)++ owner.update_column(:coupon_code, nil)+ end++ # Removes the line items a promotion's create-line-items actions added.+ def remove_promotion_line_items(owner, promotion)+ action_ids = promotion.actions.where(type: CREATE_LINE_ITEMS_ACTION_TYPES).ids+ remove_service = owner.is_a?(Spree::Cart) ? Spree.cart_remove_item_service : Spree.order_remove_item_service+ owner_key = owner.is_a?(Spree::Cart) ? :cart : :order++ Spree::PromotionActionLineItem.where(promotion_action: action_ids).find_each do |item|+ next if owner.find_line_item_by_variant(item.variant).blank?++ # The promotion is still active here, so recalculating would add its items back;+ # other promotions are still re-evaluated.+ options = owner.is_a?(Spree::Cart) ? { excluded_promotion_ids: [promotion.id] } : {}+ remove_service.call(owner_key => owner, variant: item.variant, quantity: item.quantity, options: options)+ end+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/carts/recalculate.rb b/spree/core/app/workflows/spree/carts/recalculate.rbindex 013dc66c4e..6bbbbbc594 100644--- a/spree/core/app/workflows/spree/carts/recalculate.rb+++ b/spree/core/app/workflows/spree/carts/recalculate.rb@@ -9,6 +9,8 @@ module Spree# @param cart [Spree::Cart, Spree::Order] draft orders ride the same pipeline# @param line_item [Spree::LineItem, nil] the item whose change triggered this+ # @param options [Hash] +excluded_promotion_ids:+ lists promotions to leave out of activation,+ # for callers that are removing a promotion's effectsdef perform(cart: nil, order: nil, line_item: nil, line_item_created: false, options: {})if orderSpree::Deprecation.warn('Calling Spree::Carts::Recalculate with order: is deprecated and will be removed in Spree 6.1. Pass cart: instead.')@@ -47,7 +49,9 @@ module Spreedef activate_promotions@promotion_context = run_hooks :set_promotion_context- ::Spree::PromotionHandler::Cart.new(cart, line_item).activate+ ::Spree::PromotionHandler::Cart.new(+ cart, line_item, excluded_promotion_ids: options[:excluded_promotion_ids] || []+ ).activateendendenddiff --git a/spree/core/lib/tasks/remove_orphan_order_promotions.rake b/spree/core/lib/tasks/remove_orphan_order_promotions.rakenew file mode 100644index 0000000000..e1000a5098--- /dev/null+++ b/spree/core/lib/tasks/remove_orphan_order_promotions.rake@@ -0,0 +1,20 @@+# frozen_string_literal: true++# Deleting a promotion used to leave OrderPromotion rows on open carts pointing+# at a promotion that no longer exists, which broke loading those carts.+namespace :spree do+ desc 'Remove order promotions whose promotion no longer exists and recalculate the affected carts'+ task remove_orphan_order_promotions: :environment do+ orphans = Spree::OrderPromotion.where.not(promotion_id: Spree::Promotion.unscoped.select(:id))+ removed = 0++ orphans.find_each do |order_promotion|+ owner = order_promotion.owner+ order_promotion.destroy+ owner&.recalculate_totals! if owner.is_a?(Spree::Cart)+ removed += 1+ end++ puts "remove_orphan_order_promotions done. removed: #{removed}"+ end+enddiff --git a/spree/core/spec/lib/tasks/remove_orphan_order_promotions_spec.rb b/spree/core/spec/lib/tasks/remove_orphan_order_promotions_spec.rbnew file mode 100644index 0000000000..bce5a6f03c--- /dev/null+++ b/spree/core/spec/lib/tasks/remove_orphan_order_promotions_spec.rb@@ -0,0 +1,45 @@+require 'spec_helper'+require 'rake'++describe 'spree:remove_orphan_order_promotions' do+ subject { Rake::Task['spree:remove_orphan_order_promotions'] }++ before(:all) do+ Rake::Task.define_task(:environment)+ load Spree::Core::Engine.root.join('lib', 'tasks', 'remove_orphan_order_promotions.rake')+ end++ before { subject.reenable }++ let(:store) { @default_store }+ let(:promotion) do+ create(:promotion_with_order_adjustment, code: 'save10', weighted_order_adjustment_amount: 10, store: store)+ end+ let(:cart) { create(:cart_with_line_items, line_items_count: 1, store: store) }++ before do+ cart.coupon_code = promotion.code+ Spree::PromotionHandler::Coupon.new(cart).apply+ end++ it 'removes order promotions whose promotion is gone and keeps the others' do+ kept_cart = create(:cart_with_line_items, line_items_count: 1, store: store)+ other = create(:promotion_with_order_adjustment, code: 'other5', weighted_order_adjustment_amount: 5, store: store)+ kept_cart.coupon_code = other.code+ Spree::PromotionHandler::Coupon.new(kept_cart).apply+ Spree::Promotion.unscoped.where(id: promotion.id).delete_all++ expect { silence_output { subject.invoke } }.to change(Spree::OrderPromotion, :count).by(-1)++ expect(cart.reload.order_promotions).to be_empty+ expect(kept_cart.reload.order_promotions.count).to eq(1)+ end++ def silence_output+ original = $stdout+ $stdout = StringIO.new+ yield+ ensure+ $stdout = original+ end+enddiff --git a/spree/core/spec/models/spree/promotion_destroy_with_open_cart_spec.rb b/spree/core/spec/models/spree/promotion_destroy_with_open_cart_spec.rbnew file mode 100644index 0000000000..8824fe79a9--- /dev/null+++ b/spree/core/spec/models/spree/promotion_destroy_with_open_cart_spec.rb@@ -0,0 +1,74 @@+require 'spec_helper'++describe Spree::Promotion, type: :model do+ describe 'destroying a promotion that an open cart is using' do+ let(:store) { @default_store }+ let(:promotion) { create(:promotion_with_order_adjustment, code: 'save10', weighted_order_adjustment_amount: 10, store: store) }+ let(:cart) { create(:cart_with_line_items, line_items_count: 1, store: store) }++ before do+ cart.coupon_code = promotion.code+ Spree::PromotionHandler::Coupon.new(cart).apply+ cart.reload+ end++ it 'applies the code to the cart' do+ expect(cart.promotions).to contain_exactly(promotion)+ expect(cart.discount_total).to be_negative+ end++ it 'is allowed, because no placed order uses the promotion' do+ expect(promotion.destroy).to be_truthy+ end++ it 'leaves the cart readable' do+ promotion.destroy++ expect { cart.reload.order_promotions.map(&:name) }.not_to raise_error+ end++ it 'removes the promotion and its discount from the cart' do+ promotion.destroy+ cart.reload++ expect(cart.order_promotions).to be_empty+ expect(cart.discount_total).to be_zero+ end++ it 'is still blocked, and leaves the cart alone, when a placed order uses the promotion' do+ order = create(:completed_order_with_totals, store: store)+ Spree::OrderPromotion.create!(order: order, promotion: promotion)++ expect(promotion.destroy).to be_falsey+ expect(cart.reload.order_promotions.count).to eq(1)+ expect(cart.discount_total).to be_negative+ end+ end++ describe 'destroying an automatic promotion that added a gift to an open cart' do+ let(:store) { @default_store }+ let(:gift) { create(:variant) }+ let(:promotion) { create(:promotion, kind: :automatic, code: nil, store: store) }+ let(:cart) { create(:cart_with_line_items, line_items_count: 1, store: store) }++ before do+ action = Spree::Promotion::Actions::CreateLineItems.create!(promotion: promotion)+ action.promotion_action_line_items.create!(variant: gift, quantity: 1)+ Spree.cart_recalculate_workflow.call(cart: cart)+ cart.reload+ end++ it 'starts with the gift in the cart' do+ expect(cart.line_items.map(&:variant)).to include(gift)+ end++ it 'removes the gift and does not add it back' do+ promotion.destroy+ cart.reload++ expect(cart.line_items.map(&:variant)).not_to include(gift)+ expect(cart.order_promotions).to be_empty+ expect(cart.item_total).to eq(cart.line_items.sum(&:amount))+ end+ end+enddiff --git a/spree/core/spec/models/spree/promotion_handler/cart_spec.rb b/spree/core/spec/models/spree/promotion_handler/cart_spec.rbindex 9ded49a898..fad0d24448 100644--- a/spree/core/spec/models/spree/promotion_handler/cart_spec.rb+++ b/spree/core/spec/models/spree/promotion_handler/cart_spec.rb@@ -19,6 +19,20 @@ module Spreeendend+ context 'with excluded_promotion_ids' do+ subject { Cart.new(order, line_item, excluded_promotion_ids: [promotion.id]) }++ let!(:action) { Promotion::Actions::CreateItemAdjustments.create(promotion: promotion, calculator: calculator) }+ let(:other_promotion) { create(:promotion, name: 'Other', store: order.store, kind: :automatic) }++ before { Promotion::Actions::CreateItemAdjustments.create(promotion: other_promotion, calculator: calculator) }++ it 'leaves the excluded promotion alone and still activates the others' do+ expect { subject.activate }.to change { line_item.discounts.count }.by(1)+ expect(line_item.discounts.map { |d| d.promotion_action.promotion }).to contain_exactly(other_promotion)+ end+ end+context 'activates in LineItem level' dolet!(:action) { Promotion::Actions::CreateItemAdjustments.create(promotion: promotion, calculator: calculator) }let(:adjustable) { line_item }diff --git a/spree/core/spec/services/spree/promotions/detach_from_owner_spec.rb b/spree/core/spec/services/spree/promotions/detach_from_owner_spec.rbnew file mode 100644index 0000000000..f93b52313f--- /dev/null+++ b/spree/core/spec/services/spree/promotions/detach_from_owner_spec.rb@@ -0,0 +1,49 @@+require 'spec_helper'++describe Spree::Promotions::DetachFromOwner do+ let(:store) { @default_store }+ let(:promotion) { create(:promotion_with_order_adjustment, code: 'save10', weighted_order_adjustment_amount: 10, store: store) }+ let(:cart) { create(:cart_with_line_items, line_items_count: 1, store: store) }++ before do+ cart.coupon_code = promotion.code+ Spree::PromotionHandler::Coupon.new(cart).apply+ cart.reload+ end++ it 'removes the order promotion and discounts and recalculates the cart' do+ result = described_class.call(owner: cart, promotion: promotion, clear_coupon_code: true)++ expect(result).to be_success+ cart.reload+ expect(cart.order_promotions).to be_empty+ expect(cart.discounts.promotion).to be_empty+ expect(cart.discount_total).to be_zero+ expect(cart.coupon_code).to be_nil+ end++ it 'keeps the entered code on the cart by default' do+ described_class.call(owner: cart, promotion: promotion)++ expect(cart.reload.coupon_code).to eq('save10')+ end++ it 'keeps the promotion itself' do+ described_class.call(owner: cart, promotion: promotion)++ expect(Spree::Promotion.exists?(promotion.id)).to be(true)+ end++ context 'when the owner is a completed order' do+ let(:order) { create(:completed_order_with_totals, store: store) }++ before { Spree::OrderPromotion.create!(order: order, promotion: promotion) }++ it 'fails and leaves the order alone' do+ result = described_class.call(owner: order, promotion: promotion)++ expect(result).to be_failure+ expect(order.reload.order_promotions.count).to eq(1)+ end+ end+end